使用Python的pandas库将excel批量转为csv格式
excel文件都放在./数据样例
目录下,输出文件在./csv
目录下
-
代码如下
# 导入pandas import pandas as pd import os # 建立单个文件的excel转换成csv函数,file 是excel文件名,to_file 是csv文件名。 def excel_to_csv(file, to_file): data_xls = pd.read_excel(file, sheet_name=0) # index=False每行不添加索引 data_xls.to_csv(to_file, index=False, encoding='utf_8_sig') # 读取一个目录里面的所有文件: def read_path(path): if not os.path.exists(path): print("yes") dirs = os.listdir(path) return dirs # 主函数 def main(): # 源文件路径 source = "./数据样例" # 目标文件路径 ob = "./csv/" # 将源文件路径里面的文件转换成列表file_list file_list = [source + '/' + i for i in read_path(source)] j = 1 # 建立循环对于每个文件调用excel_to_csv() for it in file_list: # 给目标文件新建一些名字列表 name = it.split("/")[-1].split(".")[0] j_mid = str(name) j_csv = ob + '/' + j_mid + ".csv" excel_to_csv(it, j_csv) print(it) j = j + 1 if __name__ == '__main__': main()