我想要合并两个文本文件:
Firts档案:
1|Monkey
2|Tiger
3|Crane
4|Mantis
第二档:
|Brown
|Orange
|White
|Green
结果会变成这样:
1|Monkey|Brown
2|Tiger |Orange
3|Crane |White
4|Mantis|Green
任何想法如何做到这一点?
更新
啊,发现了!工作示例: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)
答案 0 :(得分:1)
可以这样做
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))