參考 https://www.jianshu.com/p/4e39444d5ebc
環境:
pip install xlwt
python3.6
將csv/txt文本通過程序轉換成excel文件,自定義分隔符
# -*- coding:utf-8 -*-
__author__ = 'zhuyuru'
#參考 https://www.jianshu.com/p/4e39444d5ebc
# from workbook import Workbook
import os
import sys
import time
# pip install xlwt
import xlwt
list = []
def parsefile(filepath, mark):
print("[info]============>parse_file")
dic = {}
try:
begin = time.time()
[des_filename, extname] = os.path.splitext(filepath)
nfilename = des_filename + '_' + str("r") + extname
# 處錯誤 就改成gb18030
f_read = open(filepath, encoding='UTF-8')
# 具體處理
rownum = 0
for eachline in f_read:
splitarr = eachline.split(mark)
list.append(splitarr)
rownum = rownum + 1
if (rownum % 10000 == 0):
print("[info]parse_file %s" % (rownum))
except:
print(sys.exc_info()[0], sys.exc_info()[1])
finally:
f_read.close()
end = time.time()
print("[info]======>format file %s ,spend time %d s" % (filepath, (end - begin)))
return dic;
def create_xls(file_path, list):
workbook = xlwt.Workbook(encoding = 'utf-8') # 注意Workbook的開頭W要大寫
sheet1 = workbook.add_sheet('sheet1', cell_overwrite_ok=True)
# 向sheet頁中寫入數據
for i, j in enumerate(list):
if (i % 10000 == 0):
print("執行到第%s行" % (i + 1))
for s, k in enumerate(j):
sheet1.write(i, s, str(k))
file_path = file_path.replace('\\', '/')
workbook.save(file_path)
print('創建excel文件完成!')
return file_path
if __name__ == '__main__':
srcfile = '/Users/zhuyuru/Desktop/temp/smslist.csv'
floder = os.path.dirname(os.path.realpath(__file__))
srcfile=floder+u'/srcdata.csv'
print("srcfile:%s"%(srcfile))
[des_filename, extname] = os.path.splitext(srcfile)
parsefile(srcfile, ',')#解析文件
create_xls(des_filename + u"_r.xls", list)#將解析後的文件輸出到excel