46

以下代码:

from pathlib import Path
Desktop = Path('Desktop')
SubDeskTop = Desktop + "/subdir"

得到以下错误:

    ---------------------------------------------------------------------------
 TypeError                                 Traceback (most recent call last)
    <ipython-input-4-eb31bbeb869b> in <module>()
             1 from pathlib import Path
             2 Desktop = Path('Desktop')
       ----> 3 SubDeskTop = Desktop+"/subdir"

     TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'

我显然在这里做了一些阴暗的事情,但它提出了一个问题:如何访问Path对象的子目录?

4

2 回答 2

83
from pathlib import Path

Desktop = Path('Desktop')

# print(Desktop)
WindowsPath('Desktop')

# extend the path to include subdir
SubDeskTop = Desktop / "subdir"

# print(SubDeskTop)
WindowsPath('Desktop/subdir')

# passing an absolute path has different behavior
SubDeskTop = Path('Desktop') / '/subdir'

# print(SubDeskTop)
WindowsPath('/subdir')
  • 当给出多个绝对路径时,最后一个被视为锚点(模仿os.path.join()的行为):
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')

>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')
  • 在 Windows 路径中,更改本地根目录不会丢弃以前的驱动器设置:
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
  • 有关提供绝对路径的附加详细信息,请参阅文档,例如Path('/subdir').

资源:

于 2018-01-10T15:41:40.057 回答
16

您正在寻找的是:

from pathlib import Path
Desktop = Path('Desktop')
SubDeskTop = Path.joinpath(Desktop, "subdir")

joinpath()函数会将第二个参数附加到第一个参数并为您添加“/”。

于 2018-01-10T15:43:54.240 回答