Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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":

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading