[英]How do I replace a text file's contents with another if they are different?
I am looking to replace one text file with the contents of another if they are not the same.如果一个文本文件不相同,我希望用另一个文本文件的内容替换它们。
Whenever I run this script, "['" and "']" are added on to the old_text.txt file, which means it will never match with new_text.txt file.每当我运行此脚本时,“['”和“']”都会添加到 old_text.txt 文件中,这意味着它永远不会与 new_text.txt 文件匹配。
How do I remove these characters so the .txt files have the exact same contents after running this script?如何删除这些字符,以便在运行此脚本后 .txt 文件具有完全相同的内容?
old_text = open('old_text.txt', 'r+')
new_text = open('new_text.txt', 'r+')
old_text_compare = str(old_text.readlines())
new_text_compare = str(new_text.readlines())
if old_text_compare != new_text_compare:
print("difference")
old_text = open('old_text.txt', 'w')
old_text.write(str(new_text_compare))
else:
print("no difference")
If you want to compare file contents directly, use .read()
rather than .readlines()
如果要直接比较文件内容,请使用
.read()
而不是.readlines()
with open('old_text.txt', 'r+') as f1, open('new_text.txt', 'r+') as f2:
old = f1.read()
new = f2.read()
if old != new:
with open('new_text.txt', 'w') as f1:
f1.write(old)
else:
print("no difference")
You want to compare the list of lines directly, like so:您想直接比较行列表,如下所示:
if old_text.readlines() != new_text.readlines():
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.