How to "join" two text files with python?
Question: I have two txt files like this: txt1:

    
    
    Foo
    Foo
    Foo
    Foo
    

txt2:

    
    
    Bar
    Bar
    Bar
    Bar
    

How can I concatenate them in a new file by the left and the right side let's
say like this:

    
    
    Bar Foo
    Bar Foo
    Bar Foo
    Bar Foo
    

I tried the following:

    
    
    folder = ['/Users/user/Desktop/merge1.txt', '/Users/user/Desktop/merge2.txt']
    with open('/Users/user/Desktop/merged.txt', 'w') as outfile:
        for file in folder:
            with open(file) as newfile:
                for line in newfile:
                    outfile.write(line)
    


Answer: Use
[`itertools.izip`](https://docs.python.org/2/library/itertools.html#itertools.izip)
to combine the lines from both the files, like this

    
    
    from itertools import izip
    with open('res.txt', 'w') as res, open('in1.txt') as f1, open('in2.txt') as f2:
        for line1, line2 in zip(f1, f2):
            res.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))
    

**Note:** This solution will write lines from both the files only till either
of the files exhaust. For example, if the second file contains 1000 lines and
the first one has only 2 lines, then only two lines from each file is copied
to the result. In case you want lines from the longest file even after the
shortest file exhausted, you can use
[`itertools.izip_longest`](https://docs.python.org/2/library/itertools.html#itertools.izip_longest),
like this

    
    
    from itertools import izip_longest
    with open('res.txt', 'w') as res, open('in1.txt') as f1, open('in2.txt') as f2:
        for line1, line2 in izip_longest(f1, f2, fillvalue=""):
            res.write("{} {}\n".format(line1.rstrip(), line2.rstrip()))
    

In this case, even after the smaller file exhausts, the lines from longer file
will still be copied and the `fillvalue` will be used for the lines from the
shorter file.

