因為用到了模塊openpyxl python自帶庫不含有 需要先安裝這個模塊。
-安裝模塊
pip install openpyxl
(當(dāng)然如果你是windows系統(tǒng)建議參照該鏈接先安裝pip 然后在執(zhí)行pip安裝安裝地址)
-環(huán)境變量一定要設(shè)置好(cmd窗口 python 和pip命令驗證)
-實現(xiàn)代碼
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import openpyxl
import csv
import os
def walkFile(file):
for root, dirs, files in os.walk(file):
# root 表示當(dāng)前正在訪問的文件夾路徑
# dirs 表示該文件夾下的子目錄名list
# files 表示該文件夾下的文件list
#轉(zhuǎn)換文件類型
Const_Image_Format = ["csv"]
# 遍歷文件
times=1
for f in files:
print('************************************************************')
csv_file_name=os.path.join(root, f)
file_name = os.path.basename(csv_file_name)
excel_file_name = file_name.split('.')[0]
file_type = file_name.split('.')[1]
print(file_type)
if file_type in Const_Image_Format :
# 創(chuàng)建工作簿對象
print('This is ' + str(times) + ' Convert Start')
work_book = openpyxl.Workbook()
# 創(chuàng)建sheet
work_sheet = work_book.create_sheet(title="sheet1")
csvfile = open(csv_file_name, 'r',encoding='UTF-8')
# 獲取csv.reader
lines = csv.reader(csvfile)
print(lines)
# row
row = 1
# csv文件中假如不包含標(biāo)題可以使用如下代碼加入
# title_list 中寫入每個標(biāo)題名稱以逗號相隔
# title_list = [u'標(biāo)題']
#
# # 寫入第一行,標(biāo)題
# for i in range(1, title_list.__len__() + 1):
# work_sheet.cell(row=row, column=i).value = title_list[i - 1]
# 寫入從csv讀取的內(nèi)容 如使用了以上代碼 這里行數(shù)要加一
for line in lines:
# print(line)
lin = 1
for i in line:
work_sheet.cell(row=row, column=lin).value = i
lin += 1
row += 1
# 關(guān)閉文件
csvfile.close()
# 保存工作表
work_book.save(excel_file_name + '.xlsx')
print('This is ' + str(times) + ' Convert End')
print('************************************************************')
#轉(zhuǎn)換過后的文件重命名
os.rename(csv_file_name,csv_file_name + 'bak')
times = times + 1
# 遍歷所有的文件夾
for d in dirs:
print(os.path.join(root, d))
def main():
walkFile(r'C:/NewPan/lzg_python/csv/')
執(zhí)行效果

執(zhí)行結(jié)果
生成文件

生成文件
轉(zhuǎn)換后文件重命名處理,防止多次轉(zhuǎn)換

轉(zhuǎn)換后重命名
源文件

源文件內(nèi)容
轉(zhuǎn)換excel后效果

轉(zhuǎn)換后excel