我在txt文件中有2个数据数组:
A1 A2 A3
A4 A5 A6
A7 A8 A9
和
B1 B2 B3
B4 B5 B6
B7 B8 B9
我想将它们并排组合:
A1 A2 A3 B1 B2 B3
A4 A5 A6 B4 B5 B6
A7 A8 A9 B7 B8 B9
(这些空格实际上是我的txt文件中的标签)
谢谢!
答案 0 :(得分:5)
从任一文本文件同时读取行。连接每次读取的行,并将结果写入新的文本文件。
答案 1 :(得分:3)
类似的东西:
>>> 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')
<强>输出:强>
A1 A2 A3 B1 B2 B3
A4 A5 A6 B4 B5 B6
A7 A8 A9 B7 B8 B9
答案 2 :(得分:0)
抽象@Ashwini对任意数量文件的回答:
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')