使用 python 从一个文件中删除存在于另一个文件中的行
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 的更新内容如下,因为 a 和 c 存在于 file_2 中:
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))
我有两个文件 - file_1 和 file_2。我需要根据 file_2 中的所有行查找 file_1 中的所有行,如果找到任何匹配项,则使用 python 代码从 file_1 中删除匹配的行。例如
file_1 的内容:
a
b
c
d
e
file_2 的内容:
a
c
我希望看到 file_1 的更新内容如下,因为 a 和 c 存在于 file_2 中:
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))