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

问题描述

我有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)

但是在我看来,您可以nuke并完全铺平文件:

from textwraps import dedent

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...