-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
  • 51,429
  • 22
  • 99
  • 91
user1551817
  • 5,613
  • 18
  • 63
  • 97

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
  • 232,417
  • 55
  • 437
  • 487
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
  • 18,799
  • 3
  • 53
  • 65
arshajii
  • 123,543
  • 24
  • 232
  • 276
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
  • 104,525
  • 25
  • 135
  • 234