An P.
An P.

Reputation: 41

Combining columns from two different text files in python

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!

Upvotes: 2

Views: 6838

Answers (1)

dokelung
dokelung

Reputation: 216

You can try this:

In Python 3:

with open('file3.txt', 'w') as file3:
    with open('file1.txt', 'r') as file1:
        with open('file2.txt', 'r') as file2:
            for line1, line2 in zip(file1, file2):
                print(line1.strip(), line2.strip(), file=file3)

If you have more than one file to be handled, you can generalize the code like:

filenames = ['file1.txt', 'file2.txt', ...]
with open('output.txt', 'w') as writer:
    readers = [open(filename) for filename in filenames]
    for lines in zip(*readers):
        print(' '.join([line.strip() for line in lines]), file=writer)

In Python 2:

with open('file3.txt', 'w') as file3:
    with open('file1.txt', 'r') as file1:
        with open('file2.txt', 'r') as file2:
            for line1, line2 in zip(file1, file2):
                print >>file3, line1.strip(), line2.strip()

Hope it is helpful!

Upvotes: 5

Related Questions