为什么 pathlib.Path("C:") 解析为 Windows 上的工作目录?

flo*_*sla 3 python pathlib

在 Windows 7 x64 上使用 Python 3.6,该路径"C:"似乎与以下内容的空路径相同Path.resolve()

“空”路径是“当前工作目录” cwd()

>>> from pathlib import Path
>>> Path().resolve()
WindowsPath('C:/Users/me')
>>> Path(r"").resolve()
WindowsPath('C:/Users/me')
>>> Path.cwd().resolve()
WindowsPath('C:/Users/me')
Run Code Online (Sandbox Code Playgroud)

单个字母被解释为文件夹名称:

>>> Path(r"C").resolve()
WindowsPath('C:/Users/me/C')
Run Code Online (Sandbox Code Playgroud)

完整的驱动器号+冒号+反斜杠按预期指向驱动器根:

>>>> Path(r"C:\").resolve()
WindowsPath('C:/')
Run Code Online (Sandbox Code Playgroud)

但是忘记了反斜杠指向当前工作目录?

>>>> Path(r"C:").resolve()
WindowsPath('C:/Users/me/C')
Run Code Online (Sandbox Code Playgroud)

我希望它要么将冒号(不带反斜杠)视为常规字符(对于Path("te:st")),要么忽略它("C"),要么将路径视为驱动器根("C:\")。但相反,它似乎完全忽略了 C。

对于其他驱动器号("A:""X:"、...),解析要么无限期挂起(不好!),要么要求我将磁盘插入驱动器(这表明它也没有完全忽略驱动器号)。

ber*_*ers 5

它不是。

至少不是解析pathlib.Path("C:")为Windows 上的工作目录

C:\Users\bersbers>d:

D:\>python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from pathlib import Path
>>> Path.cwd().resolve()
WindowsPath('D:/')
>>> Path(r"C:").resolve()
WindowsPath('C:/Users/bersbers')
>>>
Run Code Online (Sandbox Code Playgroud)

如您所见,解析了C: 驱动器上的C:最后一个活动目录,这与 Windows 使用vs.的方式完全一致:C:C:\

D:\>dir C:\
 Volume in drive C is Windows
 Volume Serial Number is 1234-ABCD

 Directory of C:\

01/17/2020  10:34 AM    <DIR>          Program Files
01/18/2020  12:11 AM    <DIR>          Program Files (x86)
...
Run Code Online (Sandbox Code Playgroud)

与此比较:

D:\>dir C:
 Volume in drive C is Windows
 Volume Serial Number is 1234-ABCD

 Directory of C:\Users\bersbers

01/20/2020  11:19 AM    <DIR>          .
01/20/2020  11:19 AM    <DIR>          ..
08/23/2018  10:45 AM    <DIR>          .cache
11/27/2019  11:26 PM             1,024 .rnd
...
Run Code Online (Sandbox Code Playgroud)

这也适用于文件路径:

D:\>copy C:\.rnd %TEMP%
The system cannot find the file specified.

D:\>copy C:.rnd %TEMP%
        1 file(s) copied.
Run Code Online (Sandbox Code Playgroud)

同样:

C:\Users\bersbers>D:

D:\>cd C:
C:\Users\bersbers

D:\>C:

C:\Users\bersbers>
Run Code Online (Sandbox Code Playgroud)

相对

C:\Users\bersbers>D:

D:\>cd C:\

D:\>C:

C:\>
Run Code Online (Sandbox Code Playgroud)

总之,Path("C:").resolve()基于长期建立的 Windows 行为,其行为完全符合您的预期。