Python 3:打开多个.csv文件

Python 3:打开多个.csv文件,csv,python-3.x,Csv,Python 3.x,我想打开多个csv文件(具有相同的数据类型/列),将数据保存到一个变量中,对数据执行一些操作并将其保存到一个csv文件中。虽然我可以轻松打开一个文件,但似乎找不到打开多个文件的方法。这是我的密码: import numpy as np import csv from collections import Counter files = ['11.csv', '12.csv', '13.csv', '14.csv', '15.csv'] with open(files) as csvfile:

我想打开多个csv文件(具有相同的数据类型/列),将数据保存到一个变量中,对数据执行一些操作并将其保存到一个csv文件中。虽然我可以轻松打开一个文件,但似乎找不到打开多个文件的方法。这是我的密码:

import numpy as np
import csv
from collections import Counter

files = ['11.csv', '12.csv', '13.csv', '14.csv', '15.csv']

with open(files) as csvfile:
    info = csv.reader(csvfile, delimiter=',')
    info_types = []
    records = 0
    for row in info:
        records = row[2]
        call_types.append(records)
stats = Counter(call_types).most_common()
print(stats)

results = stats
resultFile = open("Totals.csv",'w')
wr = csv.writer(resultFile, dialect='excel')
for output in results:
    wr.writerow(output)

为了让它工作,同时减少bug的发生率和效率,请尝试以下方法

# required imports

files = ['11.csv', '12.csv', '13.csv', '14.csv', '15.csv']

with open("outfile","wt") as fw:
    writer = csv.writer(fw)
    for file in files:
        with open(file) as csvfile:
            info = csv.reader(csvfile, delimiter=',')
            info_types = []
            records = 0
            for row in info:
                # process row but don't store it
                # in any list if you
                # don't have to(that will defeat the purpose)
                # say you get processed_row
                writer.writerow(processed_row)

我会在一个循环内完成这项工作。因为您在读取文件时已经在追加数据

for f in files:
    with open(f) as csvfile:
        ...

多谢。它像梦一样工作!现在我必须弄清楚如何跳过第一行之后每个文件的标题。@Chuck只需在信息中的行的
之前添加
header=next(info)