How to get the last part of a Path in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
6 min

banner

# Table of Contents

  1. Get the last part of a path in Python
  2. Remove the last path component from a String in Python
  3. Remove a path prefix in Python
  4. Remove the first folder from a path in Python

# Get the last part of a path in Python

Use the pathlib.PurePath class to get the last part of a path.

The name attribute on the object returns a string that represents the last part of the provided path.

main.py
import pathlib path = '/home/borislav/Desktop/last/' last_part = pathlib.PurePath(path).name print(last_part) # ๐Ÿ‘‰๏ธ 'last'

get last part of path

The code for this article is available on GitHub

If you have to process Windows-style paths on a Linux machine, use the ntpath module instead.

main.py
import ntpath def get_last_path(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) last_path = get_last_path('C:\\Users\\Borislav\\Desktop\\example.txt') print(last_path) # ๐Ÿ‘‰๏ธ example.txt

The pathlib.PurePath class represents the system's path flavor.

Instantiating the class creates either a PurePosixPath or a PureWindowsPath.

The PurePath.name attribute returns a string that represents the final path component, excluding the drive and root, if any.

main.py
import pathlib # ๐Ÿ‘‡๏ธ images print(pathlib.Path('/home/borislav/Desktop/images').name) # ๐Ÿ‘‡๏ธ example.txt print(pathlib.Path('/home/borislav/Desktop/example.txt').name) # ๐Ÿ‘‡๏ธ Desktop print(pathlib.Path('/home/borislav/Desktop/').name)
The code for this article is available on GitHub

In the unlikely scenario that you have to process Windows-style paths on a Linux machine, use the ntpath module.

main.py
import ntpath def get_last_path(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) last_path = get_last_path('C:\\Users\\Borislav\\Desktop\\example.txt') print(last_path) # ๐Ÿ‘‰๏ธ example.txt

Windows paths can use either a backlash or a forward slash as the path separator and the ntpath module handles both cases.

The ntpath.split() method returns a tuple (head, tail) where tail is everything after the final slash.

If the path doesn't end in a slash, we return tail, otherwise, we use the ntpath.basename() method to return the final component of the pathname.

Alternatively, you can use the os.path.basename() method.

# Get the last part of a path using os.path.basename()

This is a two-step process:

  1. Use the os.path.normpath() method to strip any trailing slashes from the path.
  2. Use the os.path.basename() method to get the last part of the path.
main.py
import os path = '/home/borislav/Desktop/last/' last_path = os.path.basename(os.path.normpath(path)) print(last_path) # ๐Ÿ‘‰๏ธ last

get last part of path using os path basename

The code for this article is available on GitHub

The os.path.normpath() method normalizes a path by removing double slashes and stripping trailing slashes.

The os.path.basename() method returns the final component of the path.

If used with a path that ends with a forward slash, the os.path.basename() method returns an empty string (everything after the last slash).

This is why we had to use the os.path.normpath method to strip any trailing slashes before calling os.path.basename.

If you have to process Windows-style paths on a Linux machine, use the ntpath module instead.

main.py
import ntpath def get_last_path(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) last_path = get_last_path('C:\\Users\\Borislav\\Desktop\\example.txt') print(last_path) # ๐Ÿ‘‰๏ธ example.txt

# Remove the last path component from a String in Python

To remove the last path component from a string:

  1. Use the pathlib.Path class to create a path object.
  2. Access the parent attribute on the object.
  3. The parent attribute returns the logical parent of the path.
main.py
from pathlib import Path absolute_path = '/home/bobbyhadz/Desktop/python/main.py' result = Path(absolute_path).parent print(result) # ๐Ÿ‘‰๏ธ /home/bobbyhadz/Desktop/python absolute_path = '/home/bobbyhadz/Desktop/' result = Path(absolute_path).parent print(result) # ๐Ÿ‘‰๏ธ /home/bobbyhadz
The code for this article is available on GitHub

The pathlib.Path class is used to create a PosixPath or a WindowsPath object depending on your operating system.

The parent attribute returns the logical parent of the path.

main.py
from pathlib import Path print(Path('/a/b/c').parent) # ๐Ÿ‘‰๏ธ '/a/b' print(Path('/a/b/c/').parent) # ๐Ÿ‘‰๏ธ '/a/b'

This approach works for POSIX and Windows.

Alternatively, you can use the os.path.dirname() method.

# Remove the last path component from a String using os.path.dirname()

This is a two-step process:

  1. Use the os.path.normpath() method to strip any trailing slashes from the path.
  2. Use the os.path.dirname() method to remove the last path component.
main.py
import os absolute_path = '/home/bobbyhadz/Desktop/python/main.py' result = os.path.dirname(os.path.normpath(absolute_path)) print(result) # ๐Ÿ‘‰๏ธ /home/bobbyhadz/Desktop/python absolute_path = '/home/bobbyhadz/Desktop/' result = os.path.dirname(os.path.normpath(absolute_path)) print(result) # ๐Ÿ‘‰๏ธ /home/bobbyhadz
The code for this article is available on GitHub

The os.path.normpath() method normalizes a path by removing double slashes and stripping trailing slashes.

The os.path.dirname() method returns the directory component of a pathname.

The os.path.dirname() method wouldn't work if the path ends with a slash.

main.py
import os absolute_path = '/home/bobbyhadz/Desktop/' result = os.path.dirname(absolute_path) print(result) # ๐Ÿ‘‰๏ธ /home/bobbyhadz/Desktop

This is why we had to use the os.path.normpath method to strip any trailing slashes before calling os.path.dirname.

# Remove a path prefix in Python

You can use the os.path.relpath() method if you need to remove a path prefix.

The relpath() method takes the path and a start directory and returns a relative file path to the given path.

main.py
import os absolute_path = '/home/bobbyhadz/Desktop/python/main.py' relative_path = '/home/bobbyhadz' without_prefix = os.path.relpath(absolute_path, relative_path) print(without_prefix) # ๐Ÿ‘‰๏ธ Desktop/python/main.py
The code for this article is available on GitHub

The os.path.relpath() method returns a relative file path to the given path from the current directory or from the provided start directory.

main.py
import os absolute_path = '/home/bobbyhadz/Desktop/python/main.py' # ๐Ÿ‘‡๏ธ bobbyhadz/Desktop/python/main.py print(os.path.relpath(absolute_path, '/home')) # ๐Ÿ‘‡๏ธ Desktop/python/main.py print(os.path.relpath(absolute_path, '/home/bobbyhadz')) # ๐Ÿ‘‡๏ธ python/main.py print(os.path.relpath(absolute_path, '/home/bobbyhadz/Desktop'))

Note that the filesystem is not accessed to confirm the existence of the provided path or start arguments.

main.py
import os absolute_path = '/home/bobbyhadz/Desktop/python/main.py' # ๐Ÿ‘‡๏ธ ../home/bobbyhadz/Desktop/python/main.py print(os.path.relpath(absolute_path, '/abc'))

On Windows, if path and start are on different drives, a ValueError exception is raised.

Alternatively, you can use the PurePath.relative_to() method.

# Remove a path prefix using PurePath.relative_to()

This is a three-step process:

  1. Use the PurePath class to create a path object.
  2. Use the relative_to() method to remove the path prefix.
  3. The relative_to() method returns the relative path to the provided path.
main.py
from pathlib import PurePath absolute_path = '/home/bobbyhadz/Desktop/python/main.py' a_path = PurePath(absolute_path) without_prefix = str(a_path.relative_to('/home/bobbyhadz')) print(without_prefix) # ๐Ÿ‘‰๏ธ Desktop/python/main.py
The code for this article is available on GitHub

The pathlib.PurePath class represents the system's path flavor.

Instantiating the class creates either a PurePosixPath or a PureWindowsPath.

The PurePath.relative_to() method returns the relative path to another path identified by the provided arguments.

main.py
from pathlib import PurePath absolute_path = '/home/bobbyhadz/Desktop/python/main.py' a_path = PurePath(absolute_path) # ๐Ÿ‘‡๏ธ bobbyhadz/Desktop/python/main.py print(str(a_path.relative_to('/home'))) # ๐Ÿ‘‡๏ธ Desktop/python/main.py print(str(a_path.relative_to('/home/bobbyhadz'))) # ๐Ÿ‘‡๏ธ python/main.py print(str(a_path.relative_to('/home/bobbyhadz/Desktop')))

Note that the filesystem is not accessed to confirm the existence of the provided absolute and relative paths.

However, the method raises a ValueError if the strings don't match.

main.py
from pathlib import PurePath absolute_path = '/home/bobbyhadz/Desktop/python/main.py' a_path = PurePath(absolute_path) # โ›”๏ธ ValueError: '/home/bobbyhadz/Desktop/python/main.py' is not in the subpath of '/abc' OR one path is relative and the other is absolute. print(str(a_path.relative_to('/abc')))

# Remove the first folder from a path in Python

If you need to remove the first folder from a path:

  1. Use the pathlib.Path class to create a path object.
  2. Use the relative_to() method to remove the first folder.
main.py
from pathlib import Path absolute_path = '/home/bobbyhadz/Desktop/python/main.py' a_path = Path(absolute_path) result = a_path.relative_to(*a_path.parts[:2]) print(result) # ๐Ÿ‘‰๏ธ bobbyhadz/Desktop/python/main.py

The pathlib.Path class is used to create a PosixPath or a WindowsPath object depending on your operating system.

The PurePath.relative_to() method returns the relative path to another path identified by the provided arguments.

main.py
from pathlib import Path absolute_path = '/home/bobbyhadz/Desktop/python/main.py' a_path = Path(absolute_path) # ๐Ÿ‘‡๏ธ bobbyhadz/Desktop/python/main.py print(str(a_path.relative_to('/home')))

The PurePath.parts attribute returns a tuple containing the path's components.

main.py
from pathlib import Path absolute_path = '/home/bobbyhadz/Desktop/python/main.py' a_path = Path(absolute_path) # ๐Ÿ‘‡๏ธ ('/', 'home', 'bobbyhadz', 'Desktop', 'python', 'main.py') print(a_path.parts) print(a_path.parts[:2]) # ๐Ÿ‘‰๏ธ ('/', 'home')

To remove the first folder from the path, we pass the first two components of the path to the relative_to() method.

main.py
from pathlib import Path absolute_path = '/home/bobbyhadz/Desktop/python/main.py' a_path = Path(absolute_path) result = a_path.relative_to(*a_path.parts[:2]) print(result) # ๐Ÿ‘‰๏ธ bobbyhadz/Desktop/python/main.py

The slice my_tuple[:2] starts at index 0 and goes up to, but not including index 2.

In other words, the slice returns the first two elements of the tuple.

We used the iterable unpacking operator to unpack the list in the call to the relative_to method.

The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.

main.py
example = (*(1, 2), 3) # ๐Ÿ‘‡๏ธ (1, 2, 3) print(example)

Alternatively, you can split the path on the separator.

# Remove the first folder from a path using os.path.join()

This is a three-step process:

  1. Use the str.split() method to split the path on each separator.
  2. Use list slicing to select the list elements starting at index 2.
  3. Use the os.path.join() method to join the remainder of the list into a string.
main.py
import os absolute_path = '/home/bobbyhadz/Desktop/python/main.py' result = os.path.join(*(absolute_path.split(os.path.sep)[2:])) print(result) # ๐Ÿ‘‰๏ธ bobbyhadz/Desktop/python/main.py
The code for this article is available on GitHub

The os.sep attribute returns the character used by the operating system to separate pathname components.

main.py
import os print(os.path.sep) # ๐Ÿ‘‰๏ธ '/'

The separator character is / for POSIX and \\ for Windows.

We used the str.split() method to split the path on each occurrence of the separator character.

main.py
import os absolute_path = '/home/bobbyhadz/Desktop/python/main.py' # ๐Ÿ‘‡๏ธ ['', 'home', 'bobbyhadz', 'Desktop', 'python', 'main.py'] print(absolute_path.split(os.path.sep)) # ๐Ÿ‘‡๏ธ ['bobbyhadz', 'Desktop', 'python', 'main.py'] print(absolute_path.split(os.path.sep)[2:])

The last step is to unpack the list items starting at index 2 in the call to the os.path.join() method.

main.py
import os absolute_path = '/home/bobbyhadz/Desktop/python/main.py' result = os.path.join(*(absolute_path.split(os.path.sep)[2:])) print(result) # ๐Ÿ‘‰๏ธ bobbyhadz/Desktop/python/main.py

The slice my_list[2:] starts at index 2 and goes to the end of the list.

The os.path.join method joins one or more paths intelligently.

main.py
import os # ๐Ÿ‘‡๏ธ /home/bobbyhadz print(os.path.join('/', 'home', 'bobbyhadz'))
The method concatenates the provided paths with exactly one directory separator following each non-empty part except the last.

If any of the provided components is an absolute path, all previous components are thrown away and joining continues from the absolute path onwards.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev