我想比较两个文件并在其后添加一些信息。在Python中比较2个文件
我的文件1的样子:
1 234 332 4
2 345 435 6
3 546 325 3
4 984 493 9
我的文件2貌似
1 234 332 a b c d
2 345 435 a b c d
4 984 493 a b c d
而且我想下面的输出
1 234 332 4 a b c d
2 345 435 6 a b c d
4 984 493 9 a b c d
换句话说: 我想比较第1,2和3列。如果它们相等,我想要第1列的第4列,然后是第i列的其余部分N文件2.
我写了下面的代码在Python:
with open('file1.txt') as f1, open('file2.txt') as f2, open('output_file.txt', 'w') as outfile:
for line1, line2 in zip(f1, f2):
columns1 = line1.rstrip("\n").split("\t")
columns2 = line2.rstrip("\n").split("\t")
if columns1[0] == columns2[0] and columns1[1] == columns2[1] and columns1[2] == columns2[2]:
print >> outfile, columns2[0],columns2[1],columns2[2],columns1[3],columns2[3],columns2[4],columns2[5],columns2[6]
而且我得到以下结果:
1 234 332 4 a b c d
2 345 435 6 a b c d
我的问题是,我的代码是由线
比较线line1 with line1
line2 with line2
当我的代码比较line3和line3时,它们不相等,程序停止。 如何才能将line3与line4进行比较等等......如果第3行不匹配???
https://docs.python.org/3/library/difflib.html – davidism 2015-03-13 17:50:22
你的问题不是事实,你的代码是比较一行行,但你是不是每一行比较循环中的每一行。您需要嵌套循环才能交叉检查每个条目。 – Josh 2015-03-13 18:21:09