Windows path in Python

What is the best way to represent a Windows directory, for example "C:\meshes\as" ? I am trying to change a script, but it never works because I can’t get the correct directory, I suppose, because the '\' acts like an escape character?

+77
python path string-literals
Jun 01 '10 at 22:29
source share
3 answers

you can always use:

 'C:/mydir' 

this works on both Linux and windows. Another opportunity

 'C:\\mydir' 

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

 r'C:\mydir' 

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

 os.path.join(mydir, myfile) 
+125
Jun 01 '10 at 22:30
source share

Use the os.path module.

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

Or use raw strings

 r"C:\meshes\as" 
+12
Jun 01 '10 at 22:30
source share

Yes, \ in Python string literals indicate the start of an escape sequence. On your way, you have a valid two-character \a escape sequence that collapses into a single character, which is ASCII Bell :

 >>> '\a' '\x07' >>> len('\a') 1 >>> 'C:\meshes\as' 'C:\\meshes\x07s' >>> print('C:\meshes\as') C:\meshess 

Other common escape sequences include \t (tab), \n (string), \r (carriage return):

 >>> list('C:\test') ['C', ':', '\t', 'e', 's', 't'] >>> list('C:\nest') ['C', ':', '\n', 'e', 's', 't'] >>> list('C:\rest') ['C', ':', '\r', 'e', 's', 't'] 

As you can see, in all of these examples, the backslash and the next character in the literal were grouped together to form a single character in the last line. A complete list of escape sequences, Python is here .

There are many ways to deal with this:

  1. Python will not process escape sequences in string literals prefixed with r or R :

     >>> r'C:\meshes\as' 'C:\\meshes\\as' >>> print(r'C:\meshes\as') C:\meshes\as 
  2. Python on Windows should also handle slashes.

  3. You can use os.path.join ...

     >>> import os >>> os.path.join('C:', os.sep, 'meshes', 'as') 'C:\\meshes\\as' 
  4. ... or the new pathlib module

     >>> from pathlib import Path >>> Path('C:', '/', 'meshes', 'as') WindowsPath('C:/meshes/as') 
+6
Mar 31 '18 at 12:31
source share



All Articles