Pathlib如何处理以数字开头的文件夹

Pathlib how to deal with folders that start with a number

在 Windows 上使用 Python 3 路径库,除了添加额外的斜杠之外,是否有其他方法可以处理以数字开头的文件夹?

例如:

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

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

我原以为 PureWindowsPath 会解决这个问题。如果我用 op = pathlib.Path("D:\Documents\01") 手动退出它,那就没问题了。我是否总是必须手动添加反斜杠以避免转义?

""是一个值为1的字节,不是“反斜杠,零,一”。

你可以这样做,例如:

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

"D:\Documents\01" 中的额外斜杠是为了告诉 Python 你 想让它把 解释为转义顺序。

来自评论链:

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