打开文件缩进意外



我是一个在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

in my file.

我的代码只会找到以'specific-line'开头并且包含'一个', '两个'和'四个'的行。

我需要对我的代码做些什么来改变它,以便我也得到' specificline '加上'三个'和'五个''的行,但同时忽略任何其他行(标记为- '忽略这行'),我不想。

有人能帮我吗?

谢谢!div =]

你有两个问题,与你阅读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

最新更新