How two merge several .csv files horizontally with python?

后端 未结 6 583
渐次进展
渐次进展 2021-01-14 16:11

I\'ve several .csv files (~10) and need to merge them together into a single file horizontally. Each file has the same number of rows (~300) and 4 header lines which are not

6条回答
  •  长发绾君心
    2021-01-14 16:35

    Purely for learning purposes

    A simple approach that does not take advantage of csv module:

    # 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()
    

提交回复
热议问题