【问题标题】:Join txt files side by side in python [closed]在python中并排加入txt文件[关闭]
【发布时间】:2012-10-29 14:33:02
【问题描述】:

我在 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 文件中的制表符)

谢谢!

【问题讨论】:

    标签: python


    【解决方案1】:

    同时从任一文本文件中读取行。将您每次读取的行连接起来,并将结果写入一个新的文本文件。

    【讨论】:

      【解决方案2】:

      类似这样的:

      >>> 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
      

      【讨论】:

        【解决方案3】:

        抽象@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')
        

        【讨论】:

          猜你喜欢
          • 2021-10-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多