I have 4 excel files located in D:\Users\gnulch2\Desktop. 4 Excel files: Metro Scan To…
- User
I have 4 excel files located in D:\Users\gnulch2\Desktop.
4 Excel files: Metro Scan To Open Report (01-2023) SGH.xlsx Metro Scan To Open Report (02-2023) SGH.xlsx Metro Scan To Open Report (03-2023) SGH.xlsx Metro Scan To Open Report (04-2023) SGH.xlsx
In each of the excel file, there are 5 tabs. Each of the tabs contains the following header from column A to F. Header: UserID, StationName, ResourceAction, TransationTYpe, DateCreated, Bin.
Under each header are list of data.
Write a python code to combine all tabs in individual excel files. After which, combine all 4 excels files into one. Do note when combining, only row 1 contains the header, subsequent rows should containt the data only.
- Assistant
Here's a code snippet that should accomplish the task:
import pandas as pd import os # set the directory containing the excel files dir_path = 'D:\\Users\\gnulch2\\Desktop' # define a function to extract the data from each tab in an excel file def process_excel_file(file_path): # load the excel file into a pandas dataframe xls = pd.ExcelFile(file_path) # loop through each sheet in the excel file tabs = [] for tab in xls.sheet_names: # skip the header row and read in the data df = pd.read_excel(xls, tab, header=1) tabs.append(df) # concatenate all the dataframes into a single dataframe result = pd.concat(tabs) # return the combined dataframe return result # loop through each excel file in the directory and process it dataframes = [] for file_name in os.listdir(dir_path): if file_name.endswith('.xlsx'): file_path = os.path.join(dir_path, file_name) df = process_excel_file(file_path) dataframes.append(df) # concatenate all the dataframes into a single dataframe combined_df = pd.concat(dataframes) # write the combined dataframe to a new excel file combined_df.to_excel('combined.xlsx', index=False)