簡體   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