1

I am new to Python. I have two files that have sentences that I need to combine 2 files line by line into a single file.

file_1.txt: 
feel my cold hands.
I love oranges. 
Mexico has a large surplus of oil.
Ink stains don't rub out.

file_2.txt: 
≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡.
∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ.
∏flΩ√ƒ⁄ø°¥¬ ¥Ÿ∑Æ¿« ø©∫–¿« ºÆ¿Ø∞° ¿÷¥Ÿ.
¿◊≈© ¿⁄±π¿∫ ¥€æ∆µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ.



FINAL OUTPUT should look like: 

feel my cold hands.
≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡.

I love oranges. 
∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ.

Mexico has a large surplus of oil.
∏flΩ√ƒ⁄ø°¥¬ ¥Ÿ∑Æ¿« ø©∫–¿« ºÆ¿Ø∞° ¿÷¥Ÿ.

Ink stains don't rub out.
¿◊≈© ¿⁄±π¿∫ ¥€æ∆µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ.

Here is what I tried

filenames = ['data/data.txt', 'data/data2.txt']
with open('data/test.txt', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

This code here just concats the files one after another. However, it is not paring up the line by line and creating \n. Thanks!!

References: combine multiple text files into one text file using python

Python concatenate text files

sharp
  • 2,140
  • 9
  • 43
  • 80

4 Answers4

5

So the trick is we want to iterate over both files simultaneously. To do that we can use the zip function like so:

filenames = ['data/data.txt', 'data/data2.txt']
with open('data/test.txt', 'w') as outfile:
    with open(filenames[0]) as f1, open(filenames[1]) as f2:
        for f1_line, f2_line in zip(f1, f2):
            outfile.write(f1_line)
            outfile.write(f2_line)
            outfile.write("\n")  # add blank line between each pair
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
1

you can use this:

with open('data/data.txt', 'r') as f1, open('data/data2.txt', 'r') as f2:
    for line1, line2 in zip(f1, f2):
        # do something
user3375448
  • 695
  • 6
  • 14
1

You can use a context manager:

import contextlib

@contextlib.contextmanager
def aline(outfile, *files):
  final_data = zip(open(files[0]), open(files[1]))
  yield ['\n'.join([a, b]) for a, b in final_data]
  f = open(outfile, 'w')
  for a, b in final_data:
    f.write('\n'.join([a, b])+'\n\n')
  f.close()

with aline('output.txt', *['data/data.txt', 'data/data2.txt']) as f:
  print(f)

Output (int output.txt):

feel my cold hands.
≥ª ¬˘ º’¿ª ¡ª ∏∏¡Æ∫¡.

I love oranges. 
∏«¸ ∫Ò«‡±‚∞° ∞≠¿ª ≥Øæ∆∞¨¥Ÿ.

Mexico has a large surplus of oil.
∏flΩ√ƒ⁄ø°¥¬ ¥Ÿ∑Æ¿« ø©∫–¿« ºÆ¿Ø∞° ¿÷¥Ÿ.

Ink stains don't rub out.
¿◊≈© ¿⁄±π¿∫ ¥€æ∆µµ ¡ˆøˆ¡ˆ¡ˆ æ ¥¬¥Ÿ.
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
-1

Try this:

filenames = ['data/data.txt', 'data/data2.txt']
with open('data/test.txt', 'w') as outfile,ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    for lines in zip(*files):
        outfile.writelines(lines)

This approach can take any number of inputfiles.

MegaIng
  • 7,361
  • 1
  • 22
  • 35