我需要将excel转换为csv。但我不能多写csv文件
import sys,os
sys.path.insert(0,'D:/apera/Python27/xlrd-0.9.3')
import xlrd
import csv
path = "D:/apera/Workspace/Sounding"
CSVFile1 = "D:/apera/Workspace/Sounding/sounding001.csv"
CSVFile2 = "D:/apera/Workspace/Sounding/sounding002.csv"
for root,dirs,files in os.walk(path):
xlsfiles=[ _ for _ in files if _.endswith('.xls') ]
for xlsfile in xlsfiles:
wb = xlrd.open_workbook(os.path.join(root,xlsfile))
n = len(wb.sheets())
ws = wb.sheet_by_name("INPUT")
with open(CSVFile1, 'wb') as csvfile:
wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL, delimiter=';')
for rownum in xrange(ws.nrows):
wr.writerow(list(x.encode('latin1')for x in ws.row_values(rownum)))
with open(CSVFile2, 'wb') as csvfile:
wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL, delimiter=';')
for rownum in xrange(ws.nrows):
wr.writerow(list(x.encode('latin1')for x in ws.row_values(rownum)))
csvfile.close()
这是编辑过的问题。我需要编写csv文件。这只是需要写入的2个文件。所以我写了两次。那么有没有办法让它变得更简单。所以我不需要打开csvfile3,4,5等等。谢谢
答案 0 :(得分:2)
如果您的问题是关于如何使用“*”通配符打开多个文件,那么我认为您可以使用glob
模块(如您所述):
import glob
file_names = glob.glob("*.txt")
for file_name in file_names:
f = open(file_name, 'wb')
f.write("AAA")
关于python中文件名通配符的类似问题已经讨论过here。
答案 1 :(得分:0)
您可以执行以下操作(用于写入多个csv文件):
import sys,os,xlrd,csv
sys.path.insert(0,'D:/apera/Python27/xlrd-0.9.3')
path = "D:/apera/Workspace/Sounding"
files_to_write = ["D:/apera/Workspace/Sounding/sounding1.csv","D:/apera/Workspace/Sounding/sounding2.csv"]
for root,dirs,files in os.walk(path):
xlsfiles=[ _ for _ in files if _.endswith('.xls') ]
for xlsfile in xlsfiles:
wb = xlrd.open_workbook(os.path.join(root,xlsfile))
n = len(wb.sheets())
ws = wb.sheet_by_name("INPUT")
for z in files_to_write:
with open(z, 'wb') as csvfile:
wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL, delimiter=';')
for rownum in xrange(ws.nrows):
wr.writerow(list(x.encode('latin1')for x in ws.row_values(rownum)))