【问题标题】:How two merge several .csv files horizontally with python?两个如何用python水平合并几个.csv文件?
【发布时间】:2011-04-28 12:46:48
【问题描述】:

我有几个 .csv 文件 (~10),需要将它们水平合并成一个文件。每个文件具有相同的行数(~300)和 4 个标题行,它们不一定相同,但不应合并(仅从第一个 .csv 文件中获取标题行)。行中的标记用逗号分隔,中间没有空格。

作为一个 python 菜鸟,我还没有想出一个解决方案,尽管我确信这个问题有一个简单的解决方案。欢迎任何帮助。

【问题讨论】:

    标签: python file csv


    【解决方案1】:

    您可以使用 Python 中的 csv 模块加载 CSV 文件。加载代码请参考这个模块的documentation,我不记得了,但是很简单。比如:

    import csv
    reader = csv.reader(open("some.csv", "rb"))
    csvContent = list(reader)
    

    之后,当您以这种形式(元组列表)加载 CSV 文件时:

    [ ("header1", "header2", "header3", "header4"),
      ("value01", "value12", "value13", "value14"),
      ("value11", "value12", "value13", "value14"),
      ... 
    ]
    

    您可以逐行合并两个这样的列表:

    result = [a+b for (a,b) in zip(csvList1, csvList2)]
    

    要保存这样的结果,您可以使用:

    writer = csv.writer(open("some.csv", "wb"))
    writer.writerows(result)
    

    【讨论】:

    • 也许您需要在合并之前进行切片,然后执行类似的操作而不是列表理解。 a.extend(b[4:])
    【解决方案2】:

    csv 模块是你的朋友。

    【讨论】:

      【解决方案3】:

      如果你不一定要使用 Python,可以使用 paste/gawk 等 shell 工具

      $ paste file1 file2 file3 file4 .. | awk 'NR>4'
      

      上面将它们水平放置,没有标题。如果你想要标题,只需从file1获取它们

      $  ( head -4 file ; paste file[1-4] | awk 'NR>4' ) > output
      

      【讨论】:

        【解决方案4】:

        您不需要为此使用 csv 模块。你可以使用

        file1 = open(file1)
        

        打开所有文件后,您可以执行此操作

        from itertools import izip_longest
        
        foo=[]
        for new_line in izip_longest(file1,fil2,file3....,fillvalue=''):
            foo.append(new_line)
        

        这会给你这个结构(kon 已经告诉你了)。如果每个文件中有不同的行数,它也可以工作

        [ ("line10", "line20", "line30", "line40"),
          ("line11", "line21", "line31", "line41"),
          ... 
        ]
        

        在此之后,您可以将其写入一个新文件,一次获取 1 个列表

        for listx in foo:
            new_file.write(','.join(j for j in listx))
        

        PS:更多关于 izip_longest here

        【讨论】:

          【解决方案5】:

          你在实践中学习(甚至尝试)。所以,我只是给你一些提示。使用以下函数:

          如果您真的不知道该怎么做,我建议您阅读the tutorialDive Into Python 3。 (根据您对 Python 的了解程度,您要么必须通读前几章,要么直接切入文件 IO 章节。)

          【讨论】:

            【解决方案6】:

            纯粹用于学习目的

            不利用 csv 模块的简单方法:

            # open file to write
            file_to_write = open(filename, 'w')
            # your list of csv files
            csv_files = [file1, file2, ...] 
            
            headers = True
            # iterate through your list
            for filex in csv_files:
                # mark the lines that are header lines
                header_count = 0
                # open the csv file and read line by line
                filex_f = open(filex, 'r')
                for line in filex_f:
                    # write header only once
                    if headers:
                        file_to_write.write(line+"\n")
                        if header_count > 3: headers = False
                    # Write all other lines to the file
                    if header_count > 3:
                        file_to_write.write(line+"\n")
                    # count lines
                    header_count = header_count + 1
                # close file
                filex_f.close()
            file_to_write.close()
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-03-27
              • 2012-08-12
              • 2020-03-18
              • 2019-01-02
              • 2013-04-22
              • 2020-11-22
              • 2014-07-06
              • 1970-01-01
              相关资源
              最近更新 更多