Last updated: Apr 10, 2024
Reading timeยท6 min
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.
import pathlib path = '/home/borislav/Desktop/last/' last_part = pathlib.PurePath(path).name print(last_part) # ๐๏ธ 'last'
If you have to process Windows-style paths on a Linux machine, use the ntpath
module instead.
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.
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)
In the unlikely scenario that you have to process Windows-style paths on a Linux
machine, use the ntpath
module.
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.
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.
This is a two-step process:
os.path.normpath()
method to strip any trailing slashes from the
path.os.path.basename()
method to get the last part of the path.import os path = '/home/borislav/Desktop/last/' last_path = os.path.basename(os.path.normpath(path)) print(last_path) # ๐๏ธ last
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).
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.
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
To remove the last path component from a string:
pathlib.Path
class to create a path object.parent
attribute on the object.parent
attribute returns the logical parent of the path.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 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.
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.
This is a two-step process:
os.path.normpath()
method to strip any trailing slashes from the
path.os.path.dirname()
method to remove the last path component.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 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.
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
.
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.
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
os.path.relpath()
method returns a relative file path to the given path from the current directory
or from the provided start
directory.
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.
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.
This is a three-step process:
PurePath
class to create a path object.relative_to()
method to remove the path prefix.relative_to()
method returns the relative path to the provided path.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 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.
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.
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')))
If you need to remove the first folder from a path:
pathlib.Path
class to create a path object.relative_to()
method to remove the first folder.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.
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.
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.
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.
relative_to
method.The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.
example = (*(1, 2), 3) # ๐๏ธ (1, 2, 3) print(example)
Alternatively, you can split the path on the separator.
This is a three-step process:
str.split()
method to split the path on each separator.2
.os.path.join()
method to join the remainder of the list into a
string.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 os.sep attribute returns the character used by the operating system to separate pathname components.
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.
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.
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.
import os # ๐๏ธ /home/bobbyhadz print(os.path.join('/', 'home', 'bobbyhadz'))
If any of the provided components is an absolute path, all previous components are thrown away and joining continues from the absolute path onwards.
You can learn more about the related topics by checking out the following tutorials:
__main__
module in Path