导入 10 个 csv 文件并导出为 10 个 1 xlsx 工作表

Import 10 csv files and export as 10 worksheets of 1 xlsx

我有 10 csv 个文件,想将所有文件保存为 1 xlsx 个文件的 10 个工作表。

data1.csv,data2.csv,.......,data10.csv.

尝试

import glob
import numpy as np
import pandas as pd

all_datasets = pd.DataFrame()
for x in glob.glob("*.csv"):
    df = pd.read_csv(x)

# I want to export the corresponding csv files as 10 worksheets of 1 xlsx 

#initialze the excel writer
writer = pd.ExcelWriter('all_datasets_combinedworksheets.xlsx', engine='xlsxwriter')


frames = {'sheetName_1': df1, 'sheetName_2': df2,
        'sheetName_3': df3,'sheetName_4': df4}

for sheet, frame in  frames.iteritems(): # .use .items for python 3.X
    frame.to_excel(writer, sheet_name = sheet)

#critical last step
writer.save()

我愿意接受其他方法,请分享您的代码,在此先感谢

  1. 您在循环的每次迭代中都覆盖了变量 df
  2. 您没有任何名为 df1df2 等的变量,但您正在尝试使用它们来创建 frames 字典。
  3. 您从不使用 all_datasets

尝试:

import os
frames = {f: pd.read_csv(f) for f in os.listdir(path) if f.endswith(".csv")}
writer = pd.ExcelWriter('all_datasets_combinedworksheets.xlsx', engine='xlsxwriter')

for sheet, frame in frames.items():
    frame.to_excel(writer,sheet_name=sheet)

writer.save()