gpt4 book ai didi

python - 将多个 CSV 文件合并到 Python 电子表格的单独选项卡中

转载 作者:太空狗 更新时间:2023-10-30 02:52:49 30 4
gpt4 key购买 nike

我有一个代码可以在一个目录中生成多个 CSV 文件。我想在 excel 中生成一个报告,其中包含作为单独选项卡的 CSV 文件。我使用了以下代码:

import pandas as pd
import os
import csv
import glob
path = "/MyScripts"
all_files = glob.glob(os.path.join(path, "*.csv"))
df_from_each_file = (pd.read_csv(f) for f in all_files)
df_from_each_file.to_excel(writer, sheet_name='ReturnData.csv')
writer.save()

但它给出了以下错误:AttributeError: 'generator' 对象没有属性 'to_excel'不知道我哪里错了。我是否需要导入任何特定的库来解决问题?

Python 版本为 2.7

最佳答案

这里有两个问题:

  1. 您的生成器表达式允许您延迟迭代数据框对象。您不能将生成器表达式导出到 Excel 文件。
  2. 您的sheet_name 参数是一个常量。要导出到多个工作表,您需要为每个工作表指定不同的名称。

为此,您可以使用一个简单的 for 循环:

writer = pd.ExcelWriter('out.xlsx', engine='xlsxwriter')
df_from_each_file = (pd.read_csv(f) for f in all_files)

for idx, df in enumerate(df_from_each_file):
df.to_excel(writer, sheet_name='data{0}.csv'.format(idx))

writer.save()

您的工作表将被命名为 data0.csvdata1.csv 等。如果您需要文件名作为工作表名称,您可以重构逻辑并使用os 模块从路径中提取文件名:

import os

writer = pd.ExcelWriter('out.xlsx', engine='xlsxwriter')

for f in all_files:
df = pd.read_csv(f)
df.to_excel(writer, sheet_name=os.path.basename(f))

writer.save()

关于python - 将多个 CSV 文件合并到 Python 电子表格的单独选项卡中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51964001/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com