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
Yes, \
in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a
, which is collapsed into one character that 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
(line feed), \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 these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python's escape sequences is here.
There are a variety of ways to deal with that:
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
Python on Windows should handle forward slashes, too.
You could use os.path.join ...
>>> import os
>>> os.path.join('C:', os.sep, 'meshes', 'as')
'C:\\meshes\\as'
... or the newer pathlib module
>>> from pathlib import Path
>>> Path('C:', '/', 'meshes', 'as')
WindowsPath('C:/meshes/as')