python - 如何将 .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)
解决方案
如果您想要 file2 中不在 file1 中的项目,只需替换以下内容:
same = set(file1).symmetric_difference(file2)
这样:
same = set(file2)-set(file1)
推荐阅读
- php - 如何提高将 mysql 与缓存或其他数据库一起使用的应用程序性能
- wordpress - 如何访问古腾堡块中的高级自定义字段值?
- java - slf4j/log4j 使用标记进行日志记录
- javascript - React 表中的嵌套对象数组
- android - 在我的三星 Galaxy S10+ 上通过 IntelliJ/Android SDK 调试 Android 应用程序导致“安装 APK 时出错”
- ruby - 如何创建在子级之间不共享状态的类变量
- mysql - ERROR 3680 (HY000): 无法创建模式目录“test”(错误号:13 - 权限被拒绝)
- django - “'int' 对象没有属性 'save'” 从 views.py 更新模型
- python - 有没有更快的方法来获取 MNIST 数据集的本地二进制模式?
- android - 未询问存储权限