我使用以下代码将多个.csv文件中的数据合并到一个.xls文件中。使用此代码,所有数据都保存在一个工作表中,但我需要将每个文件的数据保存在单独的工作表中,但是在同一个文件中。
你能帮我解决一下这个问题吗?
import glob
import csv
csvfiles=glob.glob('*.csv')
wf=csv.writer(open('output.xls', 'wb'))
for files in csvfiles:
rd=csv.reader(open(files, 'r'))
rd.next()
for row in rd:
wf.writerow(row)
答案 0 :(得分:1)
我遇到了编码错误,因此我使用了https://docs.python.org/2/library/csv.html中的Unicode CSV阅读器。这个答案适用于Python 2.如果您需要Python 3答案,请告诉我。
import csv, codecs, cStringIO, glob, os
import xlsxwriter
class UTF8Recoder:
"""Iterator that reads an encoded stream and reencodes the input to UTF-8"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
"""A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding."""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
wb = xlsxwriter.Workbook('output.xlsx')
for csvfile in csvfiles:
ws = wb.add_worksheet(os.path.split(csvfile)[-1][:30])
with open(csvfile,'rb') as f:
ur = UnicodeReader(f)
for r, row in enumerate(ur):
for c, col in enumerate(row):
ws.write(r, c, col)
wb.close()
答案 1 :(得分:0)
或者您可以:
workbook = Workbook('../your_path/joined.xlsx')
counter = 0
for csv_file in glob.glob(os.path.join('../your_path/', '*.csv')):
sheet_name = 'Sheet_' + str(counter)
counter += 1
worksheet = workbook.add_worksheet(sheet_name)
with open(csv_file, 'rt', encoding='utf8') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet.write(r, c, col)
workbook.close()