How to concatenate working directory + backslash + variable?

I have some code that sets the working directory, then saves a file name as a variable, incorporating the current date into the filename:

os.chdir(r"‪C:\Users\me\Documents")
filename = "My_file_" + str(date.today()) + ".xlsx"

I want to concatenate these into a full filepath with a backslash, like this:

‪C:\Users\me\Documents\My_file_2022-09-23.xlsx

I’ve tried to do this with no success. This code doesn’t work because it thinks "+ filename" is a string; it returns the error "string literal is unterminated":

filepath = os.getcwd() + r'\' + filename

Adding another backslash to terminate the string removes the error and gets it to understand that filename is a variable, but I then get both backslashes in the result, as shown below:

filepath = os.getcwd() + r'\\' + filename

‪C:\Users\me\Documents\\My_file_2022-09-23.xlsx

Does anyone know how to get the desired result, please?

>Solution :

A better way to join paths is through os.path.join(), which will use a backslash or forward slash depending on the platform convention (backslash on Windows, forward slash on Unix including Linux and Mac):

filepath = os.path.join(os.getcwd(), filename)

The cause of the "unterminated string literal" error is that raw strings can’t end with a backslash. Using '\\' without the r works fine.

Leave a Reply