13.3. File Path Escape

  • Raw Strings

  • Always use raw-strings (r"...") for paths

  • Raw String turns-off escape characters

>>> print(r'C:\Users\Admin\file.txt')
>>> print('C:\\Users\\Admin\\file.txt')
>>> print('C:\Users\Admin\file.txt')
Traceback (most recent call last):
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Problem is with \Users. After escape sequence \U... Python expects hexadecimal Unicode codepoint, i.e. '\U0001F680' which is a rocket 🚀 emoticon. In this example, Python finds letter s, which is invalid hexadecimal character and therefore raises an SyntaxError telling user that there is an error with decoding bytes. The only valid hexadecimal numbers are 0123456789abcdefABCDEF and s isn't one of them.

13.3.1. Escaping Characters in Path

  • "\ " (backslash space) - escapes space

  • Note that in Python escapes in paths are not required

>>> FILE = '/tmp/my file.txt'
>>> FILE = r'/tmp/my file.txt'
>>> FILE = r'C:\Users\Admin\myfile.txt'
>>> repr(FILE)
>>> str(FILE)
>>> print(repr(FILE))
>>> print(FILE)