繁体   English   中英

如果文本文件的内容不同,如何将它们替换为另一个?

[英]How do I replace a text file's contents with another if they are different?

如果一个文本文件不相同,我希望用另一个文本文件的内容替换它们。

每当我运行此脚本时,“['”和“']”都会添加到 old_text.txt 文件中,这意味着它永远不会与 new_text.txt 文件匹配。

如何删除这些字符,以便在运行此脚本后 .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")

如果要直接比较文件内容,请使用.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")

您想直接比较行列表,如下所示:

if old_text.readlines() != new_text.readlines():
    ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM