Skip to content Skip to sidebar Skip to footer

Build A Full Path To Windows File In Python

How can I create a string that represents a Windows Path? I need to add a file that is generated dynamically to the end of the path as well. I have tried using raw strings but I ca

Solution 1:

You have a string literal, not a raw string. A raw string is a string literal with an r before it:

path = r'C:\Path\To\Folder\' + filename

Edit: Actually, that doesn't work because raw strings can't end with backslashes. If you still want to use a raw string, you could do one of the following:

path = r'C:\Path\To\Folder' + '\\' + filename
path = r'C:\Path\To\Folder\{}'.format(filename)

You could also double the backslashes:

path = 'C:\\Path\\To\\Folder\\' + filename

Yours didn't work because a backslash is a special character. For example, \n is not a backslash and an n; it is a new line. \' means to treat ' as a literal character instead of making it end the string. That means that the string does not end there, but you don't end it later in the line either. Therefore, when Python gets to the end of the line and you still haven't closed your string, it has an error. It is still better to use os.path.join(), though:

path = os.path.join(r'C:\Path\To\Folder', filename)

Solution 2:

filename = "test.txt"
path =  os.path.join(r'C:\Path\To\Folder',filename)

although really python works fine using / as a file separator on any OS

Post a Comment for "Build A Full Path To Windows File In Python"