我曾嘗試使用此代碼比較 .py 代碼的 2 個檔案,但它只限于給我最后幾行代碼,例如,如果 file1 有 2014 行,file2 有 2004 行,那么它回傳 file1 的最后 10 行,但這不是我需要提取那些在file1中但不在file2中的行。
import shutil
file1 = 'bot-proto7test.py'
file2 = 'bot-proto7.py'
with open(file1, 'r') as file1:
with open(file2) as file2:
with open ("output.txt", "w") as out_file:
file2.seek(0, 2)
file1.seek(file2.tell())
shutil.copyfileobj(file1, out_file)
uj5u.com熱心網友回復:
您可以使用集合來做到這一點:
with open(file1, 'r') as f:
set1 = {*f.readlines()}
with open(file2, 'r') as f:
set2 = {*f.readlines()}
print(set1 - set2) # it contains only line that are in first file
順便提一句。您可以使用單個with陳述句打開多個檔案!
with open("f1.txt", "r") as f1, open("f2.txt", "r") as f2:
set1, set2 = {*f1.readlines()}, {*f2.readlines()}
如果我們想保留多行,我們可以使用Counter
from collections import Counter
with open(file1, 'r') as f:
c = Counter(f.readlines())
# simple substraction won't work here if first file contains more occurences than secod
res = Counter({k: v for k, v in c.items() if k not in set2})
print(list(res.elements()))
最后,如果您還想保留順序,則需要使用原始內容:
with open(file1, 'r') as f:
original = f.readlines()
res = {*original} - set2
res = [el for el in original if el not in res]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/407624.html
標籤:
下一篇:拆分線僅獲得兩條拆分線
