Skip to content
Advertisement

Variable file name breaks excel sheet creation

I’ve a code which creates an excel in a specific field with 3 sheets:

with pd.ExcelWriter(r'C:Usersfoldertest.xlsx') as writer:
    stock_data_full.to_excel(writer, sheet_name='sheet1')
    df_final_histo.to_excel(writer, sheet_name='sheet2')
    df_final_ops.to_excel(writer, sheet_name='sheet3')

I need the file name to become a varaible and I’ve done this:

file_name = 'test'

    with pd.ExcelWriter(f'C:\\Users\folder\{file_name}.xlsx') as writer:
        stock_data_full.to_excel(writer, sheet_name='sheet1')
        #df_final_histo.to_excel(writer, sheet_name='sheet2')
        #df_final_ops.to_excel(writer, sheet_name='sheet3')

Even though the file_name is variable now, I get an error with the sheets creation and It’s blowing my mind. Any other way to make it variable?

Thanks

Advertisement

Answer

Using fr’ instead of r’ or f’ works fine.

file_name = 'test'

    with pd.ExcelWriter(fr'C:\Usersfolder{file_name}.xlsx') as writer:
        stock_data_full.to_excel(writer, sheet_name='sheet1')
        #df_final_histo.to_excel(writer, sheet_name='sheet2')
        #df_final_ops.to_excel(writer, sheet_name='sheet3')
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement