I would like to copy the data from multiple excel files and paste it existing excel file.
import os
import openpyxl
import pandas as pd
my_path = r'C://Users//greencolor//Autoreport//Load_attachments//' # Updating every monday with new files
my_path1 =r'C://Users//greencolor//Desktop//Autoreport//' # place of Master.xlsx
for filename in os.listdir(my_path): #loop though the downloaded files
if filename.startswith('PB orders Dec'): #finds the file with the name PB orders December.xlsb
dec = pd.read_excel(os.path.join(my_path, filename),
sheet_name='Raw data ',
engine='pyxlsb') #reading the specific sheet named Raw data
with pd.ExcelWriter(my_path1 + '//Maaster.xlsx', mode='a', engine=openpyxl) as writer:
dec.to_excel(writer, sheet_name='DecData', index=False) #copyes the data from PB orders December.xlsb and paste it in Master file on sheet Decdata without deleting other sheets. Basically updating all data with new data.
My problem is that I would like to do the same above mentioned operation on multiple files. For example, if in the Load_attachments
is the file named PB orders November.xlsb I want to apply the same code to that November file and so on what ever month name file has.
You can put the entire thing (minus imports) in a for loop and feed it with an array of filename beginnings:
import os
import openpyxl
import pandas as pd
fnamebegin_array = ['PB orders Jan','PB orders Feb','PB orders Mar','etc']
sheetname_array = ['JanData','FebData','MarData','etc']
for i in range(len(fnamebegin_array)): # would be 12, if there is data for each month in a year
my_path = r'C://Users//greencolor//Autoreport//Load_attachments//'
my_path1 =r'C://Users//greencolor//Desktop//Autoreport//'
for filename in os.listdir(my_path):
if filename.startswith(fnamebegin_array[i]):
month = pd.read_excel(os.path.join(my_path, filename),
sheet_name='Raw data ',
engine='pyxlsb')
with pd.ExcelWriter(my_path1 + '//Master.xlsx', mode='a', engine=openpyxl) as writer:
month.to_excel(writer, sheet_name=sheetname_array[i], index=False)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.