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

49,745

Solution 1

  • 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

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.

Share:
49,745

Related videos on Youtube

Ray Salemi
Author by

Ray Salemi

Ray Salemi, writing as Ray Daniel, is the award-winning author of the Tucker Mysteries published by Midnight Ink. Tucker is a hacker who lives in Boston and solves murders. Ray Salemi is also a senior verification consultant with Mentor Graphics. Salemi started his career in Electronic Design Automation with Gateway Design Automation, the inventors of Verilog. Since then he has worked for Cadence Design Systems, Sun Microsystems, and several startups. Ray Salemi is the author of the popular introduction to simulation, FPGA Simulation as well as the popular introduction to the UVM, The UVM Primer.

Updated on September 24, 2020

Comments

  • Ray Salemi
    Ray Salemi almost 4 years

    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?

    • Seng Cheong
      Seng Cheong about 2 years
      The current answers all understand that the OP really wanted to join another path. But what if you really wanted to append an arbitrary string (e.g. .tmp)?
    • Ray Salemi
      Ray Salemi about 2 years
      How about this? 'Path(str(orig_path)+”.tmp”)'
    • Ray Salemi
      Ray Salemi about 2 years
      Path(str(orig_path)+".tmp")
  • Ray Salemi
    Ray Salemi over 6 years
    That works, though I learned the '/' operator is overloaded to do the same thing.
  • r.ook
    r.ook over 6 years
    Good point. I mostly use the path module in os so the usage is a bit different. Path creates a path object but in os.path the returned object is a string so it couldn't call that function on itself. Good to know, TIL.
  • PatrickT
    PatrickT about 4 years
    BEWARE: SubDeskTop = Path.joinpath(Desktop, "/subdir") won't work. The slash before subdir ruins it.