1. 程式人生 > 其它 >python批量修改Excel檔案字尾csv為xlsx

python批量修改Excel檔案字尾csv為xlsx

技術標籤:python批量替換csvexcel

可以實現功能,轉換後的檔案可能有字型被加粗之類的問題,轉換後需要檢查一下。
csv_xlsx.py

import os

import pandas as pd

def csv_to_excel(readpath,savepath):
	for dirpath,dirnames,filenames in os.walk(readpath):
		for filename in filenames:
			(purefilename, extension) = os.path.splitext(filename)      # 將檔名拆分為檔名與字尾
if (extension == '.csv'): # 判斷該字尾是否為.csv檔案 old_name=os.path.join(dirpath,filename) # print(old_name) data = pd.read_csv(old_name,encoding="gbk") data = data.astype(str) new_name = filename.split(".")[0]+".xlsx" # new_name = filename2+".xlsx"
# print(os.path.join(savepath,new_name)) data.to_excel(os.path.join(savepath,new_name),sheet_name='Sheet1',encoding="gbk",index=False) if __name__ == '__main__': path1 = r'儲存csv檔案的資料夾路徑' path2 = r'csv字尾檔案轉換為xlsx後儲存的資料夾路徑' csv_to_excel(path1,path2) print("執行完畢,轉換成功")