BladeMight BladeMight - 1 month ago 5
Python Question

Combine different text's lines as table

I want to combine two text files:

Firts fileļ¼š

1|Monkey
2|Tiger
3|Crane
4|Mantis


Second file:

|Brown
|Orange
|White
|Green


That in result the would become this:

1|Monkey|Brown
2|Tiger |Orange
3|Crane |White
4|Mantis|Green


Any ideas how to do this?

Update:

Ah, found it! The working example:

txt1="""1|Monkey
2|Tiger
3|Crane
4|Mantis"""
txt2="""|Brown
|Orange
|White
|Green"""
txt3=txt2.splitlines(True)
a=0
r=""
for l in txt1.splitlines():
r = r+ l + txt3[a]
if a < len(txt1.splitlines(True)):
a = a+1
print(r)

Answer

Can be done this way

with open('first.txt', 'r') as ffile, open('second.txt', 'r') as sfile, open('result.txt', 'w') as rfile:
    for lines in zip(ffile.read().splitlines(), sfile.read().splitlines(keepends=True)):
        rfile.write(''.join(lines))