python 实现批量xls文件转csv文件的方法
引言:以前写的一个批量xls转csv的python简单脚本,用的是python2.7
#coding=utf-8
importos
importtime
importlogging
importxlrd
importcsv
#xls文件存放路径
INPUTPATH=u"D:\\lsssl\\桌面\\xls文件"
#生成的csv文件存放路径
OUTPATH=u"D:\\lsssl\桌面\\csv"
classchangeCenter:
def__init__(self):
pass
defgetvalue(self,filename):
self.mData=[]
xlsfile=xlrd.open_workbook(filename)
table=xlsfile.sheet_by_index(0)#sheet1
rownum=table.nrows#行
colsnum=table.ncols#列
foriinrange(0,rownum):
row=[]
forjinrange(0,colsnum):
value=table.cell_value(i,j)
ifnotisinstance(value,float):
value=value.encode('gbk')#非数字转一下码
row.append(value)
self.mData.append(tuple(row))
defwrite(self,path,filename):
ifnotos.path.exists(path):
os.makedirs(path)
csvfile=file("tmp","wb")
writer=csv.writer(csvfile)
writer.writerows(self.mData)
csvfile.close()
ifos.path.exists(os.path.join(path,filename+".old")):
os.remove(os.path.join(path,filename+".old"))
ifos.path.exists(os.path.join(path,filename)):
os.rename(os.path.join(path,filename),os.path.join(path,filename+".old"))
os.rename('tmp',os.path.join(path,filename))
logging.info("writefilefinish")
print"write",filename,"finish"
defhandleExcel():
files,dirs,root=readFilename(INPUTPATH)
forfiinfiles:
strstock=os.path.join(INPUTPATH,fi)
ifos.path.exists(strstock):
st=changeCenter()
st.getvalue(strstock)
name=fi.replace(".xls","")
st.write(OUTPATH,name+".csv")
else:
printstrstock+"don'texist"
#获取某个路径下的所有文件
defreadFilename(file_dir):
forroot,dirs,filesinos.walk(file_dir):
returnfiles,dirs,root
if__name__=='__main__':
handleExcel()
以上这篇python实现批量xls文件转csv文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。