2014-07-07 130 views
0

我是一个在Python中开发的新手我有一个很好的搜索,看看我能否在发布之前回答我的问题,但我的搜索是空白的。打开文件缩进意想不到

我打开一个带有随机缩进的文件,我想通过它找到一个特定的行并在稍后将其写入另一个文件中。对于这一点,我使用:

with open("test.txt", "r+") as in_file: 
buf = in_file.read().strip() 
in_file.close() 
out_file = open("output.txt", "w+") 
for line in buf: 
    if line.startswith("specific-line"): 
     newline == line + "-found!" 
     out_file.append(newline) 
    out_file.close() 

虽然我的代码加载并读取没有任何问题的文件,我挣扎的事情是怎么不理我“的test.txt”文件中的压痕。

例如:

我可能有。

ignore this line 
ignore this line 
specific-line one 
specific-line two 
ignore this line 
    specific-line three 
specific-line four 
     specific-line five 
ignore this line 
ignore this line 

在我的文件中。

我的代码,因为它代表只能找到与“特定行”开头的行,并有“一个”,“”和他们“”。

什么我需要做的,我的代码来改变它,这样我也与也“特定行”加号“”和“”得到线,但同时忽略任何其他行(标记为'忽略此行'),我不想要。

任何人都可以帮助我吗?

谢谢! =]

回答

4

您有两个问题,与您在in_file中阅读的方式有关。行:

buf = in_file.read().strip() 

会从一开始就和结束整个文件,那么只有strip空白:

for line in buf: 

实际上是迭代字符。另外,如果您使用with,则不需要close

相反,尝试:

with open("test.txt") as in_file, open("output.txt", "w+") as out_file: 
    for line in map(str.strip, in_file): 
     if line.startswith(...): 
      ... 

此外,作为Brionius指出的评论,你比较(==),而不是分配(=)到newline,这将导致一个NameError

+3

此外,他们使用“==”,他们的意思是使用“=”。将其添加到您的答案和+1中。 – Brionius

+0

@Brionius好点,加了 – jonrsharpe

+0

谢谢!!!它工作得很好! – user3223818

相关问题