Python:将多个文件从xls转换为csv
我正在尝试在Python 2.7中编写一个脚本,将当前目录中的所有.xls和.xlsx文件转换为.csv并保留其原始文件名。
在其他类似问题的帮助下(不幸的是,我不知道该借用哪些代码),以下是迄今为止我所得到的结果:
import xlrd import csv import os def csv_from_excel(xlfile): wb = xlrd.open_workbook(xlfile) sh = wb.sheet_by_index(0) your_csv_file = open(os.path.splitext(sxlfile)[0], 'wb') wr = csv.writer(your_csv_file, dialect='excel', quoting=csv.QUOTE_ALL) for rownum in xrange(sh.nrows): wr.writerow(sh.row_values(rownum)) your_csv_file.close() for file in os.listdir(os.getcwd()): if file.lower().endswith(('.xls','.xlsx')): csv_from_excel(file)
我有两个问题:
1)我无法弄清楚为什么程序运行时,只转换一个文件,并不遍历当前目录中的所有文件。
2)我不知道如何通过转换保留原始文件名。 也就是说,输出文件与input名称相同。
谢谢
一个可能的解决scheme是使用glob
和pandas
。
excel_files = glob('*xls*') for excel in excel_files: out = excel.split('.')[0]+'.csv' df = pd.read_excel(excel, 'Sheet1') df.to_csv(out)