繁体   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

目前它覆盖每个 excel 文件表,但我希望每个 CSV 文件在 excel 上制作一个新表

它重写现有的 excel 文件,因为 ExcelWriter 是在循环内定义的。 您只需要通过在循环外定义它来创建 excel 一次,并且应该使用循环向它们添加工作表。 下面的代码对我有用

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()
    

我刚刚修改了你的 function。请注意,要将你的 Dataframe 读入 csv,pd.read_csv() 就是 function。

您使用了 pd.DataFrame(csv_file),我认为这是不正确的阅读方式。

您会在与文件夹相同的路径中找到 output.xlsx。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM