I am trying to combine two text files together.The first file has two columns, and the second file has 5 columns. Here is an example of how the files look like:
file1.txt
333333 1
423232 1
244311 2
333333 2
and so on...
file2.txt
1 4 0 5 32
3 2 3 32 23
3 4 4 2 2
and so on ...
Both files have the same number of lines. I want to combine file1.txt with file2.txt to create a new file3.txt that is of the form:
file3.txt
333333 1 1 4 0 5 32
423232 1 3 2 3 32 23
244311 2 3 4 4 2 2
and so on
I wrote this code that merges file1.txt and file2.txt together.However, what I get is a file that adds the contents of file2.txt at the end of file1.txt, which is not what I want. I get something like this:
333333 1
423232 1
244311 2
333333 2
1 4 0 5 32
3 2 3 32 23
3 4 4 2 2
Here is my code:
filenames =['file1.txt','file2.txt']
with open('file3.txt', 'w') as outfile:
for x in filenames:
with open(x) as infile:
for line in infile:
outfile.write(line)
How can I fix this code so that I get a file like file3.txt,that is,add the rows of file2.txt to corresponding rows of file1.txt? Any suggestions/help will be appreciated. Thanks!
paste -d ' ' file1.txt file2.txt > file3.txt