2017-04-03 30 views
1

非常新,请好好解释清楚。谢谢:)Python:从文件中提取单行文件

我试过如何在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 [ '#'] =数据

TypeError:'builtin_function_or_method'对象不支持项目分配

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

回答

3

正确的if语句和压痕,

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

这工作,如果我捣鼓它一点。而不是“打印行”,我留在我的“splitdata = data.split()”,以获得所需的输出格式。 – Liquidity

0

这是一个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. 
+0

如果我明白,我需要的是这样的:如果 line.startswith [ '#']: 组=数据 但设置是不正确的 – Liquidity

+0

@Liquidity我已经编辑了答案。 'startswith'方法返回布尔结果。 –

+0

这是不正确的(检查你的括号) – abccd

0

虽然你是比较新的,你应该开始学习使用列表理解,这里是你如何为例可以用它来处理你的情况。我解释了评论中的细节,评论与相应的订单相匹配。

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