我想打开多个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)
答案 0 :(得分:0)
为了使其有效,同时减少容易出错并高效尝试以下方法。
# 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)
答案 1 :(得分:0)
我会在循环中执行此操作。由于您在读取文件时已经附加了数据。
for f in files:
with open(f) as csvfile:
...