python 实现批量xls文件转csv文件的方法

yipeiwu_com5年前Python基础

引言:以前写的一个批量xls转csv的python简单脚本,用的是python2.7

#coding=utf-8
import os
import time
import logging
import xlrd
import csv
 
#xls文件存放路径
INPUTPATH= u"D:\\lsssl\\桌面\\xls文件"
 
#生成的csv文件存放路径
OUTPATH = u"D:\\lsssl\桌面\\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 #行
  colsnum = table.ncols #列
  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')#非数字转一下码
    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"
 
#获取某个路径下的所有文件 
def readFilename(file_dir):
 for root, dirs, files in os.walk(file_dir): 
  return files,dirs,root
 
if __name__ == '__main__':
 handleExcel()

以上这篇python 实现批量xls文件转csv文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用Windows批处理和WMI设置Python的环境变量方法

大概在Python2.7.xx以前,安装Python时环境变量是需要自己设的,所以自己做了一个批处理文件.bat来设置环境变量Path,通过WMI命令wmic来实现。 ::检查pat...

Python中的localtime()方法使用详解

 localtime()方法类似gmtime()方法,但它转换秒数为本地时间。如果不设置秒时或None,所返回的当前时间使用time()方法。在dst标志被设置为1时,夏令时适...

Python FFT合成波形的实例

使用Python numpy模块带的FFT函数合成矩形波和方波,增加对离散傅里叶变换的理解。 导入模块 import numpy as np import matplotlib.py...

pytorch训练imagenet分类的方法

1、imagenet数据准备: a、下载数据集 b、提取training data: mkdir train && mv ILSVRC2012_img_train.tar train...

Win10+GPU版Pytorch1.1安装的安装步骤

Win10+GPU版Pytorch1.1安装的安装步骤

安装cuda 更新nvidia驱动 打开GeForce Game Ready Driver或在GeForce Experience中下载符合自己gpu的程序。 选择cuda 打开nvi...