Python: save output file with the logged-in username appended to the file name

29 views Asked by At

I have a python program that creates an output file. That all works correctly. However, I'd now like to save the python output file with a "_username" appended to the filename.

I have included the following in my code:

import getpass

username = getpass.getuser()

output_excel_file = (r'C:\Users\name\OneDrive\Outputs\Outputs_{username}.xlsx')

This works except it saves the file as Outputs_{username}.xlsx instead of Outputs_tomsmith.xlsx

Why am i not getting the value of the variable in my path file name?

I've tried using getpass, but the variable doesn't seem to be populating with the value of the variable being passed.

1

There are 1 answers

0
Kayvan Shah On

Use f-string to format it correctly.

import getpass

username = getpass.getuser()

output_excel_file = rf"C:\\Users\\name\\OneDrive\\Outputs\\Outputs_{username}.xlsx"

or the format method

output_excel_file = 'C:\\Users\\name\\OneDrive\\Outputs\\Outputs_{}.xlsx'.format(username)