我有一个py脚本(来自Comparing large files with grep or python的alexander),用于调试两个字符串列表。你知道吗
现在我想修改它以调试列表并删除重复的字符串:
filename_1 = 'A.txt'
filename_2 = 'B.txt'
filename_3 = 'C.txt'
with open(filename_1, 'r') as f1, open(filename_2, 'r') as f2, open(filename_3, 'w') as fout:
s = set(val.strip() for val in f1.readlines())
for row in f2:
row = row.strip()
if row not in s:
fout.write(row + '\n')
清单内容:
A.txt
string1
string2
B.txt
string1
string3
预期结果:
C.txt
string1
string2
string3
谢谢
警察:我是新来的,我道歉。我真正需要的是从列表A中删除B的内容。无论如何,谢谢。你知道吗
这是答案,经过研究(3个案例):
从A.txt列表中删除B.txt内容并退出到C.txt
a=set(line.strip().lower() for line in open('A.txt').readlines())
b=set(line.strip().lower() for line in open('B.txt').readlines())
open("C.txt", "w").write("\n".join(a.difference(b)))
比较A.txt和B.txt,并在C.txt中显示新行B.txt
a=set(line.strip().lower() for line in open('A.txt').readlines())
b=set(line.strip().lower() for line in open('B.txt').readlines())
open("C.txt", "w").write("\n".join(b.difference(a)))
将A.txt和B.txt的内容合并到C.txt中
a=set(line.strip().lower() for line in open('A.txt').readlines())
b=set(line.strip().lower() for line in open('B.txt').readlines())
open("C.txt", "w").write("\n".join(b | a))
文件的第一部分包含
f2
中那些不在f1
中的项,因此只需将f1
的所有内容添加到结果中即可。你知道吗相关问题 更多 >
编程相关推荐