close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I append a string to a Path in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

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

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

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

  2. I append a string to a Path in Python

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

Method 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').

Method 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.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read