2015-03-13 71 views
-1

我想比較兩個文件並在其後添加一些信息。在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行不匹配???

+0

https://docs.python.org/3/library/difflib.html – davidism 2015-03-13 17:50:22

+0

你的問題不是事實,你的代碼是比較一行行,但你是不是每一行比較循環中的每一行。您需要嵌套循環才能交叉檢查每個條目。 – Josh 2015-03-13 18:21:09

回答

0

如果你不希望你的文件太大,爲什麼不直接遍歷每行的每一行,然後在/如果你找到一個匹配的時候中斷(假設你期望每行不超過一個匹配)。

f1 = open('file1.txt') 
f2 = open('file2.txt') 
outfile = open('output_file.txt', 'w') 

for line1 in f1: 
    columns1 = line1.rstrip("\n").split("\t") 
    for line2 in f2: 
     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] 
      break 
f1.close() 
f2.close() 
outfile.close() 
+0

您的回答對我來說似乎是正確的,但仍然無效(同樣的問題,腳本停在匹配的最後一行,忘記了以下幾行) – Pol 2015-03-16 08:43:44