pythonpython-3.xpathlib

How do I append a string to a Path?


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?


Solution

  • 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')
    
    >>> PurePath('/etc', '/usr', 'lib64')
    PurePosixPath('/usr/lib64')
    
    >>> PureWindowsPath('c:/Windows', 'd:bar')
    PureWindowsPath('d:bar')
    
    >>> PureWindowsPath('c:/Windows', '/Program Files')
    PureWindowsPath('c:/Program Files')
    

    Resources: