如何解决为什么将不正确的输出附加到我的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()
"""))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。