-4

I have 2 arrays of data in txt files:

A1 A2 A3
A4 A5 A6
A7 A8 A9

and

B1 B2 B3
B4 B5 B6
B7 B8 B9

I would like to combine them side by side:

A1 A2 A3 B1 B2 B3
A4 A5 A6 B4 B5 B6
A7 A8 A9 B7 B8 B9

(The spaces are actually tabs in my txt files)

Thank you!

Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
user1551817
  • 6,693
  • 22
  • 72
  • 109

3 Answers3

5

something like this:

>>> with open("data1.txt") as f1, open("data2.txt") as f2, open("out.txt", "w") as f3:
...     for x, y in zip(f1, f2):
...          f3.write(x.strip() + " " + y.strip() + '\n')

output:

A1 A2 A3 B1 B2 B3
A4 A5 A6 B4 B5 B6
A7 A8 A9 B7 B8 B9
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
4

Read lines simultaneously from either text file. Concatenate the lines you read each time, and write the result to a new text file.

Pierre GM
  • 19,809
  • 3
  • 56
  • 67
arshajii
  • 127,459
  • 24
  • 238
  • 287
0

To abstract @Ashwini's answer to any number of files:

filepaths = list_of_filepaths
with open('path/to/output') as f:
    for lines in zip(*[open(fpath for fpath in filepaths)]):
        outfile.write('\t'.join(line.strip() for line in lines) + '\n')
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241