Home > Software engineering >  Variable file name breaks excel sheet creation
Variable file name breaks excel sheet creation

Time:09-21

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

with pd.ExcelWriter(r'C:\Users\folder\test.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

CodePudding user response:

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

file_name = 'test'

    with pd.ExcelWriter(fr'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')
  • Related