2

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!

1
  • 3
    if you have unix like system, try paste -d ' ' file1.txt file2.txt > file3.txt Commented May 6, 2016 at 4:42

1 Answer 1

5

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!

Sign up to request clarification or add additional context in comments.

3 Comments

I get the following error: print(line1.strip(), line2.strip(), file=file3) ^ SyntaxError: invalid syntax
If you are using Python2, please use the lower one to try.
Thank you! I should have specified that I was using python 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.