【问题标题】:Combining columns of multiple files in one file - Python将多个文件的列组合到一个文件中 - Python
【发布时间】:2014-04-14 23:21:54
【问题描述】:

我有数百个包含大量信息的文本文件。每个文件有 3 列(前两列对于所有文件都相同)。 我需要将所有文件的第三列合并到一个新文件中。并插入一个列标题,其中包含该列所属文件的名称。

具有这样三列的txt文件:

-118.33333333333279 40.041666666667908 11.409999847412109
-118.29166666666612 40.041666666667908 11.090000152587891
-118.24999999999946 40.041666666667908 10.920000076293945
-118.20833333333279 40.041666666667908 10.949999809265137

我尝试创建的 txt 文件应该如下所示:

Name_of_file_1 Name_of_file_2 Name_of_file_3
3rd_Column_File_1 3rd_Column_File_2 3rd_Column_File_3
3rd_Column_File_1 3rd_Column_File_2 3rd_Column_File_3
3rd_Column_File_1 3rd_Column_File_2 3rd_Column_File_3
3rd_Column_File_1 3rd_Column_File_2 3rd_Column_File_3

这可能吗?我找不到这样做的方法。请帮忙!!!

佩波

【问题讨论】:

    标签: python merge text-files


    【解决方案1】:

    这是一种方法。内嵌代码注释:

    import csv
    
    # List of your files
    file_names = ['file1', 'file2']
    
    # Output list of generator objects
    o_data = []
    
    # Open files in the succession and 
    # store the file_name as the first
    # element followed by the elements of
    # the third column.
    for afile in file_names:
        file_h = open(afile)
        a_list = []
        a_list.append(afile)
        csv_reader = csv.reader(file_h, delimiter=' ')
        for row in csv_reader:
            a_list.append(row[2])
        # Convert the list to a generator object
        o_data.append((n for n in a_list))
        file_h.close()
    
    # Use zip and csv writer to iterate
    # through the generator objects and 
    # write out to the output file
    with open('output', 'w') as op_file:
        csv_writer = csv.writer(op_file, delimiter=' ')
        for row in list(zip(*o_data)):
            csv_writer.writerow(row)
    op_file.close()
    

    【讨论】:

      【解决方案2】:

      我会为此使用 unix 工具:

      mkfifo pipe1
      mkfifo pipe2
      mkfifo pipe3
      
      cut -d " " -f 3 text1.csv > pipe1 &
      cut -d " " -f 3 text2.csv > pipe2 &
      cut -d " " -f 3 text3.csv > pipe3 &
      
      paste pipe1 pipe2 pipe3 > final.csv
      
      rm pipe1 pipe2 pipe3
      

      所用工具的链接:

      您可以使用上面的代码示例来开发您自己的shell脚本。

      【讨论】:

      • 好主意,但这种解决方案对于任意数量的文件并不灵活,尤其是数百个文件。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      相关资源
      最近更新 更多