如何将字符串附加到 Python 中的路径?

How do I append a string to a Path in Python?

以下代码:

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 对象的子目录?

  • 扩展 pathlib 对象的正确 operator/
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')

资源:

您要找的是:

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

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