python to achieve batch xls file to csv file method

  • 2020-12-26 05:47:28
  • OfStack

Introduction: I wrote a simple python script for batch xls to csv before, using python2.7


#coding=utf-8
import os
import time
import logging
import xlrd
import csv
 
#xls File storage path 
INPUTPATH= u"D:\\lsssl\\ desktop \\xls file "
 
# The generated csv File storage path 
OUTPATH = u"D:\\lsssl\ desktop \\csv"
 
 
class changeCenter:
 def __init__(self):
  pass
 def getvalue(self,filename):
  self.mData = []
  xlsfile=xlrd.open_workbook(filename)
  table = xlsfile.sheet_by_index(0)#sheet1
  rownum = table.nrows # line 
  colsnum = table.ncols # column 
  for i in range(0,rownum):
   row = []
   for j in range(0,colsnum):
    value = table.cell_value(i,j)
    if not isinstance(value,float):
     value = value.encode('gbk')# The Numbers turn 1 Under the code 
    row.append(value)
   self.mData.append(tuple(row))
 def write(self, path, filename):
  if not os.path.exists(path):
   os.makedirs(path)
  csvfile = file("tmp","wb")
  writer = csv.writer(csvfile)
  writer.writerows(self.mData)
  csvfile.close()
  
  if os.path.exists(os.path.join(path,filename+".old")):
   os.remove(os.path.join(path,filename+".old"))
  if os.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("write file finish")
  print "write",filename," finish"
 
 
def handleExcel():
 files,dirs,root = readFilename(INPUTPATH)
 for fi in files:
  strstock = os.path.join(INPUTPATH,fi)
  if os.path.exists(strstock):
   st = changeCenter()
   st.getvalue(strstock)
   name = fi.replace(".xls","")
   st.write(OUTPATH, name+".csv")
  else:
   print strstock+" don't exist"
 
# Gets all files in a path  
def readFilename(file_dir):
 for root, dirs, files in os.walk(file_dir): 
  return files,dirs,root
 
if __name__ == '__main__':
 handleExcel()

Related articles: