Reputation: 480
I have two text files:
text1.txt:
jose 50 0.037
maria 30
fernando 20 0.489
martin 45 0.078
andres 47
text2.txt:
maria 150 0.91
martin 200 0.76
andres 350 0.67
I would like to reproduce this one:
maria 150 0.91 30
martin 200 0.76 45 0.078
andres 350 0.67 47
that is to say, a combined file containing only values from common elements in the first column. Thanks.
Upvotes: 1
Views: 202
Reputation: 71451
You can create two dictionaries from each input source to use to check for common names:
d1 = (lambda x:{a:b for a, *b in x})([i.strip('\n').split() for i in open('file1.txt')])
d2 = (lambda x:{a:b for a, *b in x})([i.strip('\n').split() for i in open('file2.txt')])
with open('file3.txt', 'w') as f:
for a, b in d1.items():
if a in d2:
f.write(f"{a} {' '.join(d2[a]+b)}\n")
Output:
maria 150 0.91 30
martin 200 0.76 45 0.078
andres 350 0.67 47
Upvotes: 2