簡體   English   中英

從一個文件替換另一個文件的文本

[英]Replacing text from one file from another file

f1.write(line2)可以工作,但它不會替換文件中的文本,而只是將其添加到文件中。 我希望file1與file2相同(如果它們不同),方法是用file2中的文本覆蓋file1中的文本

這是我的代碼:

 with open("file1.txt", "r+") as f1, open("file2.txt", "r") as f2:
     for line1 in f1:
         for line2 in f2:
             if line1 == line2:
                 print("same")
             else:
                 print("different")
                 f1.write(line2)
             break
 f1.close()
 f2.close()

我希望file1與file2相同

import shutil
with open('file2', 'rb') as f2, open('file1', 'wb') as f1:
    shutil.copyfileobj(f2, f1)

由於您不必讀取file1,因此速度會更快。

您的代碼無法正常工作,因為您必須將文件的當前指針(使用f1.seek()放置在正確的位置才能編寫該行)。

在您的代碼中,您首先讀取一行,然后將指針放置在剛讀取的行之后。 寫入時,該行數據將被寫入該位置的文件中,從而復制該行。

由於行的大小可以不同,因此進行這項工作並不容易,因為即使正確放置了指針,如果對某行進行了修改以使其變大,則在寫入時會覆蓋文件中下一行的一部分。 無論如何,您最終將不得不至少將一部分文件內容緩存在內存中。

最好截斷文件(擦除其內容)並直接寫入其他文件數據-這樣它們將是相同的。 這就是答案中的代碼。

我將read兩個文件,創建一個替換了不同元素的新list ,然后將整個列表寫入該文件

with open('file2.txt', 'r') as f:
    content = [line.strip() for line in f]

with open('file1.txt', 'r') as j:
    content_a = [line.strip() for line in j]
    for idx, item in enumerate(content_a):
        if content_a[idx] == content[idx]:
            print('same')
            pass
        else:
            print('different')
            content_a[idx] = content[idx]

with open('file1.txt', 'w') as k:
    k.write('\n'.join(content_a))

file1.txt之前:

 chrx@chrx:~/python/stackoverflow/9.28$ cat file1.txt this that this that who #replacing that what blah 

code輸出:

 same same same same different same same same 

file1.txt之后:

 chrx@chrx:~/python/stackoverflow/9.28$ cat file1.txt this that this that vash #replaced who that what blah 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM