12.3. File Path Problem

12.3.1. Recap

  • Raw Strings

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

  • Raw String turns-off escape characters

  • "\ " (backslash space) - escapes space

  • Note that in Python escapes in paths are not required

>>> print(r'C:\Users\Admin\file.txt')
C:\Users\Admin\file.txt
>>> print('C:\\Users\\Admin\\file.txt')
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.

12.3.2. Setup

>>> from pathlib import Path
>>> Path('/tmp/myfile.txt').unlink(missing_ok=True)

12.3.3. 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)
"'C:\\\\Users\\\\Admin\\\\myfile.txt'"
>>>
>>> str(FILE)
'C:\\Users\\Admin\\myfile.txt'
>>>
>>> print(repr(FILE))
'C:\\Users\\Admin\\myfile.txt'
>>>
>>> print(FILE)
C:\Users\Admin\myfile.txt