我在 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 文件中的制表符)
谢谢!
我在 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 文件中的制表符)
谢谢!
从任一文本文件中同时读取行。连接您每次读取的行,并将结果写入一个新的文本文件。
像这样的东西:
>>> 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
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')