Windows path in Python


Question

What is the best way to represent a Windows directory, for example "C:\meshes\as"? I have been trying to modify a script but it never works because I can't seem to get the directory right, I assume because of the '\' acting as escape character?

1
102
3/31/2018 11:46:58 AM

Accepted Answer

you can use always:

'C:/mydir'

this works both in linux and windows. Other posibility is

'C:\\mydir'

if you have problems with some names you can also try raw string literals:

r'C:\mydir'

however best practice is to use the os.path module functions that always select the correct configuration for your OS:

os.path.join(mydir, myfile)

From python 3.4 you can also use the pathlib module. This is equivelent to the above:

pathlib.Path(mydir, myfile)

or

pathlib.Path(mydir) / myfile
163
12/28/2018 5:14:46 AM

Use the os.path module.

os.path.join( "C:", "meshes", "as" )

Or use raw strings

r"C:\meshes\as"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon