简体   繁体   English

如何为文件夹中的每个 csv 文件在 excel 中创建一个新工作表

[英]How do I create a new sheet in excel for every csv file I have in my folder

import os
import pandas as pd
from glob import glob
import pathlib
import fileinput
import sys
import xlsxwriter

def csv_folder_input(folder):
    path = sys.path[0]
    path = path + "/" + folder
    os.chdir(path)
    counter = 1
    for filename in os.listdir(path):
        if filename.endswith(".csv"):
            with open(filename, 'r') as csvfile:
                df = pd.DataFrame(csvfile)
                with pd.ExcelWriter('output.xlsx') as writer:
                    df.to_excel(writer, sheet_name='sheet '+str(counter), index=False)
                    writer.save()
                    counter = counter + 1

Currently it overrides each excel file sheet, but I want each CSV file to make a new sheet on excel目前它覆盖每个 excel 文件表,但我希望每个 CSV 文件在 excel 上制作一个新表

It re-writes the existing excel file because the ExcelWriter is defined inside the loop.它重写现有的 excel 文件,因为 ExcelWriter 是在循环内定义的。 You need to create an excel only once by defining it outside the loop and should add sheets to them using the loop.您只需要通过在循环外定义它来创建 excel 一次,并且应该使用循环向它们添加工作表。 The below code worked for me下面的代码对我有用

def csv_folder_input(folder):
path = sys.path[0]
path = path + "/" + folder
os.chdir(path)
counter = 1
with pd.ExcelWriter('output.xlsx') as writer:
    for filename in os.listdir(path):
        if filename.endswith(".csv"):
            with open(filename, 'r') as csvfile:
                df = pd.DataFrame(csvfile)
            df.to_excel(writer, sheet_name=filename, index=False)
            print(f"Added sheet to excel: {filename}")
            counter = counter + 1
writer.save()
writer.close() 

  
def csv_folder_input(folder):
    path = sys.path[0]
    path = os.path.join(path,folder)
    os.chdir(path)
    counter=1
    writer = pd.ExcelWriter('output.xlsx')
    for filename in os.listdir(path):
        if filename.endswith(".csv"):
            print(filename)
        with open(filename, 'r') as csvfile:
            counter=counter+1
            print(counter)
            df = pd.read_csv(csvfile)
            df.to_excel(writer,sheet_name=os.path.splitext(filename)[0]+'_'+str(counter),index=False)
    writer.save()
    writer.close()
    

I have just modified your function. Please note that to read your Dataframe into a csv, pd.read_csv() is the function.我刚刚修改了你的 function。请注意,要将你的 Dataframe 读入 csv,pd.read_csv() 就是 function。

You have used pd.DataFrame(csv_file), which I believe is the incorrect way to read it.您使用了 pd.DataFrame(csv_file),我认为这是不正确的阅读方式。

You will find your output.xlsx in the same path as your folder.您会在与文件夹相同的路径中找到 output.xlsx。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我有一个包含许多列和许多行的 CSV 文件。 如何从 Python 创建一列一 Excel 表? - I have a CSV file with many columns and many rows. How do I create a one column one Excel sheet from Python? 如何使用python动态创建新的Excel工作表? - How do I create a new excel sheet dynamically using python? 我如何每分钟自动将一个新的 csv 文件从我的本地电脑导入到谷歌表格? - How do i automatically import a new csv file from my local pc to google sheets every minute? 如何更新我的破折号,其中每 15 秒将新记录附加到 csv 文件? - How do I update my dash figure where new records are appended to a csv file every 15 seconds? 如何为 Excel 文件中的每个工作表创建多个 DataFrame? - How do I create several DataFrames for each sheet in an Excel file? 如何获取从副本创建的新文件夹/工作表的ID? - How do I get the ID of a new folder/sheet that I have created from a copy? 如何在特定文件夹上创建一个空的 csv 文件? - How do I create an empty csv file on a specific folder? 如何使用 Jupyter 笔记本在 Pandas 中打印出我在 csv 文件中的每个数据值 - How do I print out every value of data I have inside my csv file in Pandas using Jupyter notebook 我如何训练我的DNNClassifier模型(在tensorflow中),以从新的训练案例中学习? 我无权访问初始CSV文件 - How do I train my DNNClassifier model (in tensorflow), to learn from new training cases? I do not have access to the initial CSV file 如何将我的 python output 放入 csv 或 ZBF57C906FA7D2BB66D07372E41585D9 文件中? - How do I get my python output into a csv or excel file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM