为什么将不正确的输出附加到我的 python 文件中?

Why is the incorrect output being appended to my python file?

我有 python 文件试图修改这里的另一个 python 文件:

file = "PythonFile1.py"

with open(file, "r") as current_file:
    lines = current_file.readlines()
for line in lines:
    if line != 'sys.stdout = open("test.txt", "w")' or line != "sys.stdout.close()" or line != "import sys":
        del lines[lines.index(line)]
with open(file, "w") as current_file:
    for line in lines:
        current_file.write(line)

print(lines)

这是试图修改的 python 文件:

import sys
sys.stdout = open("test.txt", "w")
sys.stdout.close()

当我 运行 第一个 python 文件时,我在另一个 python 文件中得到了这个结果。

sys.stdout = open("test.txt", "w")

我正在寻找的文件内容是:

import sys
sys.stdout = open("test.txt", "w")
sys.stdout.close()

我不确定为什么它没有捕捉到我想留下的线,任何人都可以帮助解决这个问题吗?

with open(file, "w") as current_file:
    current_file.write('\n'.join(lines))

不用循环写,直接连线写一次即可。当您循环遍历它时,除非您使用追加模式,否则每次循环都会替换文件中已有的内容。把台词连起来直接写会更容易


Read more about the join method

我会这样做:

magic_lines = [
    "sys.stdout = open('test.txt', 'w')",
    "sys.stdout.close()",
    "import sys"
]

with open(infilepath, 'r') as infile:
    lines = infile.readlines()

with open(infilepath, 'w') as outfile:
    for line in lines:
        if line.strip() in magic_lines:
            outfile.write(line)

但在我看来你可以用核武器完全铺平文件:

from textwraps import dedent

with open(infilepath, 'w') as infile:
    infile.write(dedent("""\
        import sys
        sys.stdout = open("test.txt", "w")
        sys.stdout.close()
    """))