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

PythonPython 3.xPathlib

Python Problem Overview


The following code:

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

gets the following error:

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

I'm clearly doing something shady here, but it raises the question: How do I access a subdirectory of a Path object?

Python Solutions


Solution 1 - Python

  • The correct operator to extend a pathlib object is /
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')
  • When several absolute paths are given, the last is taken as an anchor (mimicking os.path.join()’s behavior):
>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')

>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')
  • In a Windows path, changing the local root doesn’t discard the previous drive setting:
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
  • Refer to the documentation for addition details pertaining to giving an absolute path, such as Path('/subdir').

Resources:

Solution 2 - Python

What you're looking for is:

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

the joinpath() function will append the second parameter to the first and add the '/' for you.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRay SalemiView Question on Stackoverflow
Solution 1 - PythonRay SalemiView Answer on Stackoverflow
Solution 2 - Pythonr.ookView Answer on Stackoverflow