[英]Delete lines from one file that exist in another using python
我有兩個文件 - file_1 和 file_2。 我需要根據 file_2 中的所有行查找 file_1 中的所有行,如果找到任何匹配項,則使用 python 代碼從 file_1 中刪除匹配的行。 例如
file_1 的內容:
a
b
c
d
e
file_2 的內容:
a
c
我希望看到 file_1 的更新內容如下,因為 file_2 中存在 a 和 c:
b
d
e
我試着打開文件並將兩個文件的內容放在兩個不同的列表中,打算做一個減號但有點卡在這里。 你能給我一些建議嗎? 謝謝。
可能有更優雅的方式,但試試這個:
# read both files
with open('file_one.txt') as f:
file_one = f.read().splitlines()
with open('file_two.txt') as f:
file_two = f.read().splitlines()
# method 1 by stephan berger:
result = list(set(file_one)^set(file_two))
# method 2:
for idx_one, line_one in enumerate(file_one):
for idx_two, line_two in enumerate(file_two):
if line_two == line_one:
print(f"Removing duplicate: {line_two}")
file_one.pop(idx_one)
# write new file
with open("output.txt", "w") as f:
for line in result: # file_one for method 2
f.write(line + "\n")
print("Generated output.txt")
將每個文件的元素放在 2 個列表 l1 和 l2 中。
並使用集合:
結果 = 列表(集合(l1)^集合(l2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.