有没有办法用xlsxwriter创建多个excel文件?
from itertools import chain
import glob ,csv, sys, os
openSoundingFile = 'D:/apera/Workspace/Sounding2/*.txt'
for filename in glob.glob(openSoundingFile):
newName = filename
spamReader = csv.reader(open(filename, 'rb'), delimiter=';',quotechar='"')
workbook = xlsxwriter.Workbook('D:/apera/Workspace/Sounding2/' + newName[:-4] + '.xlsx'
sheet = workbook.add_worksheet('Original data')
for rowx, row in enumerate(spamReader):
for colx, value in enumerate(row):
sheet.write(rowx, colx, value)
workbook.close()
所以我想将所有txt文件保存到exel文件中。我认为问题出在这里
workbook = xlsxwriter.Workbook('D:/apera/Workspace/Sounding2/' + newName[:-4] + '.xlsx'
如果我没有使用+ newName[:-4] +
,它将起作用,但只能写入1个excel文件。有办法吗?
答案 0 :(得分:2)
错误显示您将文件的路径组合在一起两次:
'D:/apera/Workspace/Sounding2/bla.txtD:/apera/Workspace/Sounding2/'
这适合我:
import xlsxwriter
import glob ,csv
openSoundingFile = 'D:/apera/Workspace/Sounding2/*.txt'
for filename in glob.glob(openSoundingFile):
spamReader = csv.reader(open(filename, 'rb'), delimiter=';',quotechar='"')
# Note that filename is the full path already! Just [:-4] to remove .txt
workbook = xlsxwriter.Workbook(filename[:-4] + '.xlsx')
sheet = workbook.add_worksheet('Original data')
for rowx, row in enumerate(spamReader):
for colx, value in enumerate(row):
sheet.write(rowx, colx, value)
workbook.close()