[英]How to looping copy data from one excel sheet to another with same filename with pandas
I have 5 folder which contain 50 excel file with same file name.我有 5 个文件夹,其中包含 50 个具有相同文件名的 excel 文件。 I want to create loop to join that excel, but in different sheet.
我想创建循环来加入 excel,但在不同的工作表中。 Let's say the first folder named Task, second one attendance, performance, course, and the last one is misc.
假设第一个文件夹名为 Task,第二个文件夹是出席、表现、课程,最后一个文件夹是 misc。 The folder name = sheet name.
文件夹名称 = 工作表名称。 For the first time, i just to have joining 10 excel files in 2 folders.
第一次,我只需要在 2 个文件夹中加入 10 个 excel 文件。 But it getting more.
但它越来越多。 To join the excel files in task folder with excel files in attendance folder, i'm using this code and do all of those one by one.
要加入任务文件夹中的 excel 文件和出勤文件夹中的 excel 文件,我正在使用此代码并一一完成所有这些。 But i get so overwhelmed if i do all of those things one by one.
但是,如果我一件一件地做所有这些事情,我会感到不知所措。 Can someone help me to create a loop by this code to get the output like expected result?
有人可以帮助我通过此代码创建一个循环以获得 output 的预期结果吗?
Thank you!谢谢!
import pandas as pd
import glob
from openpyxl import load_workbook
#By task no prefix
path_task = r"C:\Users\runner\Documents\reportschool\Task\SocialA2.xlsx"
book = load_workbook(path_task)
writer = pd.ExcelWriter(path_task, engine = 'openpyxl', mode = 'a')
writer.book = book
#joined
attendance = pd.read_excel(r"C:\Users\runner\Documents\reportschool\Attendances\SocialA2.xlsx")
attendance.to_excel(writer, sheet_name = 'Attendance', index = False)
writer.save()
writer.close()
If you know names of folders then put them on list and use for
-loop如果您知道文件夹的名称,则将它们放在列表中并使用
for
-loop
all_names = ['Attendance', 'Performance', 'Course', 'Misc']
for name in all_names:
path = r"C:\Users\runner\Documents\reportschool\{}\SocialA2.xlsx".format(name)
data = pd.read_excel(path)
data.to_excel(writer, sheet_name=name, index=False)
And later you can use glob
to get folders and extract names to list all_names
using string
functions, or os.path
functions.稍后您可以使用
glob
获取文件夹并提取名称以使用string
函数或os.path
函数列出all_names
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.