如何使用Python水平合并多个.csv文件?

3
我有几个.csv文件(约10个),需要将它们横向合并成一个单独的文件。每个文件都有相同数量的行(约300行)和4个标题行,这些行不一定相同,但不应该被合并(只需从第一个.csv文件中获取标题行)。行中的标记用逗号分隔,之间没有空格。
作为Python新手,我还没有想出解决方案,但我相信这个问题有一个简单的解决方案。欢迎任何帮助。
6个回答

6
您可以使用Python中的csv模块来加载CSV文件。请参考该模块的文档以获取加载代码,我无法记住它,但它非常容易。类似这样:
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:]) - anijhaw

2

CSV模块是您的好帮手。CSV是一种常用于存储和交换数据的文件格式。


1

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

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

以上代码将它们水平排列,没有表头。如果你需要表头,只需从file1获取即可。

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

1

你不需要使用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"),
  ... 
]

接下来,您可以一次处理一个列表,将其写入新文件中

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

PS: 更多有关izip_longest的信息在这里


0

仅供学习目的

一种简单的方法,不利用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()

0

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

如果你真的不知道该怎么做,我建议你阅读教程Dive Into Python 3。(根据你了解的Python的程度,你可以阅读前几章或直接跳到文件IO章节。)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接