[英]how to write multiple csv files in python
I need to convert excel to csv. 我需要将excel转换为csv。 But i can't multi write the csv file 但我不能多写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()
This the edited question. 这是编辑过的问题。 I need to write the csv files. 我需要编写csv文件。 This is only 2 files that needs to write. 仅需要写入2个文件。 So I write it two times. 所以我写了两次。 So is there a way to make it simpler. 有没有一种方法可以使它更简单。 So I don't need to with open csvfile3, 4, 5 and so on.. Thanks 因此,我不需要打开csvfile3、4、5等。.谢谢
If your question is about how to open multiple files using the "*" wildcard, then I think you could use the glob
module (as you have already mentioned): 如果您的问题是关于如何使用“ *”通配符打开多个文件,那么我认为您可以使用glob
模块(如您已经提到的):
import glob
file_names = glob.glob("*.txt")
for file_name in file_names:
f = open(file_name, 'wb')
f.write("AAA")
And similar question regarding the filename wildcards in python was already discussed here . 关于python中文件名通配符的类似问题已在此处讨论。
You can do something like this (for writing to multiple csv files): 您可以执行以下操作(用于写入多个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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.