在Python中加入/合并文本文件(带ID)

时间:2016-03-25 16:29:03

标签: python merge

我是python编程的新手。

我可以合并表格,但现在我必须合并/连接具有特定ID的表格时遇到麻烦。

我有两个.txt文件!

在txt1中我有数字(ID),如:

5
3
4
1
2

在txt2中,我有ID坐标

1 733786 102807
2 734475 102995
3 735009 103403
4 734878 103728
5 735694 103722

我想得到一个类似于(或类似)的结果,在那里我可以看到txt1中数字旁边的正确坐标并保持顺序

5 735694 103722
3 735009 103403
4 734878 103728
1 733786 102807
2 734475 102995

我试图使用此代码

with open("1.txt", "r") as a, open("2.txt", "r") as b:
    h = {line1.strip():line2.strip() for line1,line2 in zip(a,b)}
with open("RESULT.txt", "w") as out:
    for k,v in h.iteritems():
        out.write("{} {}\n".format(k,v))

但它给出了以下结果,其中连接是好的,但顺序不是,而且很重要

1 4 734878 103728
3 2 734475 102995
2 5 735694 103722
5 1 733786 102807
4 3 735009 103403

2 个答案:

答案 0 :(得分:1)

with open("text2") as f:
     data = dict(row.split(None,1) for row in f)
with open("output.txt","wb") as f_out,open("text1") as f:
     for line in f:
         f_out.write("%s %s" % (line.strip,data.get(line.strip(),""))

答案 1 :(得分:0)

这应该可以解决问题。欢迎来到SO。下次请告诉我们您到目前为止所尝试的内容,以便我们更好地为您提供帮助。

with open('txt1.txt') as file1:
    txt1 = file1.read().splitlines()

with open('txt2.txt') as file2:
    txt2 = file2.read().splitlines()

with open('txt1.txt', 'w') as new_file:
    new = ''
    for line_a in txt1:
        for line_b in txt2:
            if line_a[0] == line_b[0]:
                new_file.write(line_b + '\n')