Python: 从文件中提取单行

Python: Extract single line from file

很新,请慢慢解释清楚。谢谢:)

我已经尝试搜索如何在 python 中提取单行,但所有响应似乎比我正在寻找的要复杂(和令人困惑)得多。我有一个文件,它有很多行,我想只提取以 # 开头的行。

我的file.txt:

"##STUFF"                                                                                                       
"##STUFF"                                                                                                       
#DATA 01 02 03 04 05
More lines here
More lines here
More lines here

我对脚本的尝试:

file = open("file.txt", "r")

splitdata = []

for line in file:
    if line.startswith['#'] = data
    splitdata = data.split()
    print splitdata

#expected output:
#splitdata = [#DATA, 1, 2, 3, 4, 5]

我得到的错误:

line.startswith['#'] = 数据

类型错误:'builtin_function_or_method'对象不支持项目分配

这似乎意味着它不喜欢我的“=数据”,但我不确定如何告诉它我想把以#开头的行单独保存。

这是一个需要谓词语句而不是赋值的 if 条件。

if line.startswith('#'):

startswith(...) S.startswith(prefix[, start[, end]]) -> bool

Return True if S starts with the specified prefix, False otherwise.
With optional start, test S beginning at that position.
With optional end, stop comparing S at that position.
prefix can also be a tuple of strings to try.

更正 if 语句和缩进,

for line in file:
    if line.startswith('#'):
        print line

虽然您相对较新,但您应该开始学习使用列表理解,这里是一个关于如何根据您的情况使用它的示例。我在评论里详细说明了,评论都对应了对应的顺序。

splitdata = [line.split() for line in file if line.startswith('#')]
# defines splitdata as a list because comprehension is wrapped in []
                          # make a for loop to iterate through file
                                           #checks if the line "startswith" a '#'
                                           # note: you should call functions/methods using the () not []
             # split the line at spaces if the if startment returns True