比较多列的两个制表符分隔文件并组合匹配

时间:2018-02-26 08:32:53

标签: python perl command

我需要比较前两列的两个文件,并选择匹配的文件和第二个文件的附加信息,如:

INPUT1:

0   1
2   4
5   6

输入2:

2   4  xyz
5   4  asv
0   1  qwe

输出

2   4  xyz
0   1  qwe

我在python尝试了这个但是没有正常工作;比如如果第一列有更多1,则无法提供正确的输出

#!/usr/bin/python

import sys

f1 = 'file1.txt'
f2 = 'file2.txt'

if len(sys.argv) == 3:
    f1 = sys.argv[1]
    f2 = sys.argv[2]

with open(f1) as file_1, open('out.txt', 'w') as of:
    for l1 in file_1:
        col_of_f1 = int(l1.split()[0])
        with open(f2) as file_2:
            for l2 in file_2:
                col_of_f2 = l2.split()
                if len(col_of_f2) < 1:
                    break
                col_of_f2 = int(col_of_f2[0])
                if col_of_f1 == col_of_f2:
                    of.write(l2)
                    break

1 个答案:

答案 0 :(得分:0)

初始化f1和f2

后替换为此代码
s1=open(f1,'r').read().split('\n')
s2=open(f2,'r').readlines()
of=open('out.txt','w')
ans=''
for i in s1:
    for j in s2:
         if i in j:
             ans+=j+'\n'
of.write(ans)
of.close()
相关问题