Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join rows of different files in python

Tags:

python

join

row

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

like image 765
HappyPy Avatar asked Feb 04 '26 07:02

HappyPy


2 Answers

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])
like image 188
chickity china chinese chicken Avatar answered Feb 05 '26 22:02

chickity china chinese chicken


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']
like image 45
galaxyan Avatar answered Feb 05 '26 20:02

galaxyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!