XLSX 到 CSV 并添加列

XLSX to CSV and add column

我有一个函数接受 Excel 文件输入并将每个选项卡转换为 CSV 文件。效果很好,见下文。

但是我想向每个 CSV 文件添加一个新列,例如每个文件都有一个 "Date" 列,其中包含今天的日期。我的计划是将 XLSX 加载到 Dataframe,然后在写入 CSV 之前添加该列,但是我想知道是否有更优雅的解决方案,因为某些 Excel 文件可以达到数百 MB?

def excel_to_csv(excel_file):
    print("Converting to CSV")
    with xlrd.open_workbook(excel_file) as wb:
        sheets = wb.sheets()
        for sh in sheets:
            save_file = f'{os.path.splitext(excel_file)[0]}_{sh.name}.csv'
            with open(save_file, 'w', newline="") as f:
                c = csv.writer(f)
                for r in range(sh.nrows):
                    print(sh.row_values(r))
                    c.writerow(sh.row_values(r))

谢谢,

就这样:

from datetime import date
d=date.today().isoformat()

...并在您的 CSV 写入循环中执行:

for r in range(sh.nrows):
    row=sh.row_values(r)
    row.insert(0,d)
    c.writerow(row)

或者显然您可以在不同的位置执行 row.append(d) 或 row.insert(),具体取决于您希望日期所在的列。