[英]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.