打开文件时缩进意外
我刚开始学习用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
我的代码现在只能找到那些以'specific-line'开头,并且包含'one'、'two'和'four'的行。
我需要对我的代码做些什么,才能让它也找到包含'specific-line'和'three'、'five'的行,同时忽略掉我不想要的其他行(标记为'ignore this line')呢?
有人能帮帮我吗?
谢谢!=]
1 个回答
5
你遇到了两个问题,主要是和你读取 in_file
的方式有关。你写的这一行:
buf = in_file.read().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
错误。