简体   繁体   中英

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.

How do I remove these characters so the .txt files have the exact same contents after running this script?

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()

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():
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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