我想从 File1 中提取 File2 中不存在的行
文件1
a
b
c
文件2
a
c
所以输出应该是:
b
bash 中一个可能的命令是:
comm -23 <(sort File1) <(sort File2) > File
它在 bash 中运行得很好,但我不知道如何在 Python 中正确实现。
我试过
import os
os.system("comm -23 <(sort File1) <(sort File2) > File")
而且不工作。 有什么提示吗?
最佳答案
纯 Python 解决方案怎么样?
with open('file1', 'r') as f:
lines1 = set(f.read().splitlines())
with open('file2', 'r') as f:
lines2 = set(f.read().splitlines())
print(lines1.difference(lines2))
或者以更少的内存开销:
with open('file1') as f, open('file2') as f2:
lines1 = set(map(str.rstrip, f))
print(lines1.difference(map(str.rstrip, f2)))
关于python - 我如何在 Python 中执行 comm Linux 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34426283/