2

在 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')

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

>>> Path(r"C").resolve()
WindowsPath('C:/Users/me/C')

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

>>>> Path(r"C:\").resolve()
WindowsPath('C:/')

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

>>>> Path(r"C:").resolve()
WindowsPath('C:/Users/me/C')

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

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

4

1 回答 1

2

它不是。

至少在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')
>>>

可以看到,C:解析了C: 盘上的最后一个活动目录,完全符合 Windows 使用C:vs.的方式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)
...

将其与此进行比较:

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
...

这也适用于文件路径:

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

D:\>copy C:.rnd %TEMP%
        1 file(s) copied.

同样:

C:\Users\bersbers>D:

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

D:\>C:

C:\Users\bersbers>

相对

C:\Users\bersbers>D:

D:\>cd C:\

D:\>C:

C:\>

因此,总而言之,Path("C:").resolve()它的行为与您期望的完全一样,基于长期建立的 Windows 行为。

于 2020-01-21T11:52:04.537 回答