引言:以前写的一个批量xls转csv的python简单脚本,用的是python2.7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
#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文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/lishenluo/article/details/79244176