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:

filename = "My_file_" + str( + ".xlsx"

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


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


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

Asked By: SRJCoding



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.

Answered By: Thomas
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.