首页 > 解决方案 > 如何将 .txt 与另一个进行比较并返回其中没有的内容?

问题描述

我正在尝试将一个 .txt 文件与另一个文件进行比较并返回其中没有的内容。

例如

一个.txt

a
b
c
d

二.txt

b
c
d
e

输出

e

我曾尝试使用 symmetric_difference() 但这将返回它们之间的差异。使用该示例,它将返回 e 和 a。

with open('text_one.txt', 'r') as file1:
    with open('text_two.txt', 'r') as file2:
        same = set(file1).symmetric_difference(file2)

same.discard('\n')

with open('output.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

标签: python

解决方案


如果您想要 file2 中不在 file1 中的项目,只需替换以下内容:

same = set(file1).symmetric_difference(file2)

这样:

same = set(file2)-set(file1)

推荐阅读