Python:将多个文件从 xls 转换为 csv

ave*_*ius 0 python csv excel

我正在尝试在 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)
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

1)我不明白为什么程序在运行时只转换一个文件而不遍历当前目录中的所有文件。

2)我不知道如何通过转换保留原始文件名。即输出文件与输入具有相同的名称。

谢谢

gab*_*bra 5

一种可能的解决方案是使用globand 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) 
Run Code Online (Sandbox Code Playgroud)