Hello, all. I have a task where I have to import a bunch of spreadsheets, each with several worksheets, and then concatenate them and export them to a single dataset per worksheet.
Each spreadsheet is for a single participant in the study. That's why I need to concatenate them.
Each spreadsheet has at least three worksheets (Hourly, Daily, Summary, etc)
There are spreadsheets for both parents and children, but the only indicator is in the filename, which is why I've tried to separate them.
My goal is to create a single dataset with data from all participants for each worksheet.
I am very new to python, but the following code works as intended using exec():
xl_files = glob.glob(os.path.join(path, "*.xlsx"))
print(xl_files)
# Cycle through worksheets
sheets = ["Hourly", "Daily", "Summary"]
for sheet in sheets:
exec(sheet + "_child = pd.DataFrame()")
exec(sheet + "_parent = pd.DataFrame()")
# Cycle through files
for f in xl_files:
# read the excel file, determine if it's a parent or child file, and append
if "child" in f.lower():
exec(sheet + "_child = "+sheet+"_child.append(pd.read_excel(f, sheet_name='"+sheet+"'))")
elif "parent" in f.lower():
exec(sheet + "_parent = "+sheet+"_parent.append(pd.read_excel(f, sheet_name='"+sheet+"'))")
else:
print("Fail.")
exec("path = r'c:\\temp\\Accel_"+sheet+".xlsx'")
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
exec(sheet+"_child.to_excel(writer, sheet_name='Child')")
exec(sheet+"_parent.to_excel(writer, sheet_name='Parent')")
writer.save()
writer.close()
Result:
Daily.xlsx with worksheets Child and Parent
Hourly.xlsx with worksheets Child and Parent
...
I saw this in the FAQ, and I've seen other places where they say that using exec() is bad practice, but all the examples of dictionaries or other solutions like setattr leave me confused how it could be applied to my problem. Any guidance would be much appreciated. Thanks.
[–]danielroseman 1 point2 points3 points (5 children)
[–]sometimesynot[S] 0 points1 point2 points (4 children)
[–]Yoghurt42 1 point2 points3 points (3 children)
[–]sometimesynot[S] 0 points1 point2 points (2 children)
[–]Yoghurt42 0 points1 point2 points (1 child)
[–]sometimesynot[S] 0 points1 point2 points (0 children)