python - 合并多个csv文件与python中不同列的错误与writerow

标签 python csv multiple-columns large-data large-files

我有大量 csv 文件/数据帧,它们太大而无法一起存储在内存中。但是,我注意到这些数据帧之间的列大小不同。我的专栏是“ACGT”(DNA 序列)的排列。我按照 this question 的说明进行操作关于如何使用不同的列编写多个 csv,但是出现以下错误: AttributeError: 'str' 对象没有属性 'keys'。我发现this question解决该错误,但是我不确定在哪里编辑代码以使“行”对象成为字典。我还担心我的 csv 文件有一个没有标题值的索引列可能会弄乱我的代码,或者我的字段名的格式(从排列派生的 str)可能是一个问题。如果有一种方法可以用另一种语言连接多个不同的 csv 文件,我可以对此进行修改,但是我遇到了 this question as well 的问题。 。

import glob
import csv
import os

mydir = "test_csv/"

file_list = glob.glob(mydir + "/*.csv") # Include slash or it will search in the wrong directory!!
file_list

import itertools
fieldnames = []
for p in itertools.product('ACGT', repeat=8):
    fieldnames.append("".join(p))


for filename in file_list:
    with open(filename, "r", newline="") as f_in:
        reader = csv.reader(f_in)
        headers = next(reader)
with open("Outcombined.csv", "w", newline="") as f_out:
    writer = csv.DictWriter(f_out, fieldnames=fieldnames)
    for filename in file_list:
        with open(filename, "r", newline="") as f_in:
            reader = csv.DictReader(f_in)
            for line in headers:
                writer.writerow(line)

最佳答案

您只需编写一次 header ,因此请在 file_list 循环之前执行此操作:

with open('Outcombined.csv','w',newline='') as f_out: 
    writer = csv.DictWriter(f_out,fieldnames=fieldnames) 
    writer.writeheader() # write header based on `fieldnames`
    for filename in file_list: 
        with open(filename,'r',newline='') as f_in: 
        reader = csv.DictReader(f_in) 
        for line in reader: 
            writer.writerow(line) 

DictWriter 将负责将值放置在正确的标题下。

关于python - 合并多个csv文件与python中不同列的错误与writerow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60195393/

相关文章:

csv - 配置单元:为逗号分隔文件创建表/数据类型语法

amazon-web-services - Amazon Redshift - 从 CSV 复制 - 行中的单双引号 - CSV 错误的无效报价格式

python - Pandas:基于分钟的列,需要在每行添加 15 秒

python - 如何在 Ubuntu 的可执行程序中转换 python 程序 .py?

python 将一个类型绑定(bind)到一个变量

python - Pandas:使用循环和分层索引将多个 csv 文件导入数据框

pandas - 比较各个列的总和并返回最大和最小列 pandas 的名称

python - Pandas 通过多个正则表达式捕获组创建多个列

c# - 如何读取多列ListView控件的列名?

python - 根据 URL 包含的最高参数过滤 URL 的 Python 列表