简体   繁体   中英

Join/Merge text files (with ID) in Python

I am quite new in python programming.

I can merge tables but now I am in trouble when I have to merge/join tables with specific IDs.

I have two .txt files !

In txt1 I have numbers (IDs) like:

5
3
4
1
2

In txt2 I have coordinates with IDs

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

I would like to get a result something like that (or similar) where I can see the right coordinates next to the numbers in txt1 with keeping the order

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

I have tried to use this code

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))

but it gives the following result where the joins are good but the order is not and it would be important

1 4 734878 103728
3 2 734475 102995
2 5 735694 103722
5 1 733786 102807
4 3 735009 103403
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(),""))

This should do the trick. Welcome to SO. Next time please show us what you tried so far, so that we can help you better.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM