Pathlib how to deal with folders that start with a number

Viewed 204

Using Python 3 pathlib on Windows, is there a way to deal with folders that start with a number, other than adding an extra slash?

For example:

from pathlib import Path, PureWindowsPath
op = pathlib.Path("D:\Documents\01")
fn = "test.txt"
fp = outpath / fn
with fp.open("w", encoding ="utf-8") as f:
    f.write(result)

Returns error: [Errno 22] Invalid argument: 'D:\\Documents\x01\\test.txt'

I would have thought the PureWindowsPath would have taken care of this. If I manually escape out of it with op = pathlib.Path("D:\Documents\\01"), then it is fine. Do I always have to manually add a backslash to avoid the escape?

1 Answers

"\01" is a byte whose value is 1, not "backslash, zero, one".

You can do, for example:

op = pathlib.Path("D:\Documents") / "01"

The extra slash in "D:\Documents\\01" is there to tell Python that you don't want it to interpret \01 as an escape sequence.

From the comments chain:

It's the Python interpreter that's doing the escaping: \01 will always be treated as an escape sequence (unless it's in a raw string literal like r"\01"). pathlib has nothing to do with escaping in this case

Related