3

If text1

1 2 3
1 2 3 4
1 2 3
1

text2

4 5 6 7
5 6 7 8
4 5
2 3 4 5 6

and text3

8 9 10 11
9
6 7 8
7

What is the most direct way to join the rows of the different files together and write the resulting text to a file?

1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7

I tried looping through the files and use file.read() but this merges the files vertically

HappyPy
  • 9,839
  • 13
  • 46
  • 68

2 Answers2

2

I think pandas is easier, but you can do it without pandas.

file_names = ['file1.txt','file2.txt','file3.txt']
res = []
for name in file_names:
    with open(name,'rb') as f:
        res.append(f.readlines())

res = [(' '.join(map(lambda row:row.strip(),line)) + '\n') for line in zip(*res)]

output:

['1 2 3 4 5 6 7 8 9 10 11\n',
 '1 2 3 4 5 6 7 8 9\n',
 '1 2 3 4 5 6 7 8\n',
 '1 2 3 4 5 6 7\n']
galaxyan
  • 5,944
  • 2
  • 19
  • 43
2

Another option is use zip to merge the lines in the text files:

with open('text1', 'r') as f1:
    t1 = f1.readlines()

with open('text2', 'r') as f2:
    t2 = f2.readlines()

with open('text3', 'r') as f3:
    t3 = f3.readlines()

for item in zip(t1,t2,t3):
    print ' '.join([line.strip() for line in item])

result:

1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7

Edit: More generalized solution:

files = ['text1', 'text2', 'text3']

contents = []

for f in files:
    with open(f, 'r') as fn:
        contents.append(fn.readlines())

for entry in zip(contents):
    for item in entry:
        print ' '.join([line.strip() for line in item])