Pathlib module in Python offers classes and methods to quickly perform the most common tasks involving file system paths, incorporating features from several other standard modules like os.path, glob, shutil, and os.
Path classes
in Pathlib module are divided into pure paths and concrete paths. Pure paths provides only computational operations but does not provides I/O operations, while concrete paths inherit from pure paths provides computational as well as I/O operations.

Basic Use of Python Pathlib Module
Python pathlib
module provides an object-oriented way to handle filesystem paths. Here’s how we can use it to perform common filesystem operations more efficiently than with the older os
and os.path
modules.
Importing the Main Class
Before we can use any features of pathlib, we need to import the Path class from the module:
Python
Listing Subdirectories
To list all subdirectories in a directory, we can use the iterdir() method and filter for directories:
Python
from pathlib import Path
p = Path('/')
for subdir in p.iterdir():
if subdir.is_dir():
print(subdir)
Output/media
/root
/run
/home
/sbin
/var
/bin
/mnt
/opt
/lib64
/sys
/lib32
/tmp
/libx32
/usr
/etc
/boot
/proc
/dev
/srv
/lib
Listing Python Source Files in This Directory Tree
We can list all Python files (.py
) within a directory and its subdirectories using the rglob()
method, which recursively searches through the directory tree:
Python
from pathlib import Path
p = Path('/')
files = p.rglob('*.py')
for f in files:
print(f)
Output:
\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\abc.py
\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\aifc.py
\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\antigravity.py
\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\argparse.py
Navigating Inside a Directory Tree
We can navigate within a directory tree using the / operator, which is overloaded to construct new Path objects:
Python
sp = p / 'example.txt'
print(sp)
Output:
\example.txt
Querying Path Properties
pathlib allows us to easily check various properties of paths:
Python
# Check if the path is absolute
print("Is absolute:", sp.is_absolute())
# Get the file name
print("File name:", sp.name)
# Get the extension
print("Extension:", sp.suffix)
# Get the parent directory
print("Parent directory:", sp.parent)
Output:
Is absolute: False
File name: example.txt
Extension: .txt
Parent directory: \
Reading and Writing to a File
Opening a file using pathlib is straightforward with the open() method. We can read from or write to files easily:
Python
# Reading from a file
with (path / 'example.txt').open('r') as file:
content = file.read()
print(content)
# Writing to a file
with (path / 'output.txt').open('w') as file:
file.write("Hello, GFG!")
Output:
First line of text.
Second line of text.
Third line of text.
Pure Paths
As stated above, Pure paths provide purely computational operations. Objects of pure path classes provide various methods for path handling operations. Pure path object operates without actually accessing the file system. Pure Path is useful when we just want to manipulate a path and without actually accessing the operating system. We can manipulate a Windows file system path on a Unix machine or vice-versa easily by instantiating one of the pure classes.
class pathlib.PurePath(*pathsegments) :
This class helps us manage paths. It doesn’t actually interact with files on our computer but lets us work with path information easily. Upon instantiating this class will create either pathlib.PurePosixPath or pathlib.PureWindowsPath.
Example:
Python
# Import PurePath class
# from pathlib module
from pathlib import PurePath
# Instantiate the PurePath class
obj = PurePath('foo/bar')
# print the instance of PurePath class
print(obj)
class pathlib.PurePosixPath(*pathsegments) :
This is for UNIX-style paths (like those on macOS or Linux). It’s not meant for use on Windows.
Python
# Import PurePosixPath class
# from pathlib module
from pathlib import PurePosixPath
# Instantiate the PurePosixPath class
obj = PurePosixPath('foo/bar')
# print the instance of PurePosixPath class
print(obj)
class pathlib.PureWindowsPath(*pathsegments) :
This one is for Windows-style paths. If we are on a Windows computer, this class understands how paths work .
Python
# Import PureWindowsPath class
# from pathlib module
from pathlib import PureWindowsPath
# Instantiate the PureWindowsPath class
obj = PureWindowsPath('foo/bar')
# print the instance of PureWindowsPath class
print(obj)
Below are few methods provided by Pure Path classes:
PurePath.is_absolute() method :
This method is used to check whether the path is absolute or not. This method returns True if the path is absolute otherwise returns False.
- On Windows, an absolute path would start with a drive letter and a colon, like C:\Users\Username\Documents\file.txt.
- On UNIX-based systems (like macOS and Linux), it starts with a forward slash (/), such as /home/username/documents/file.txt.
Python
from pathlib import PurePath
# Example of an absolute path
p = PurePath('/user/example/document.txt')
print(p.is_absolute())
# Example of a relative path
rp = PurePath('document.txt')
print(rp.is_absolute())
PurePath.name property :
This feature lets us get the last part of a path, which is usually the file or folder name.
Python
# Python program to explain PurePath.name property
# Import PurePath class from pathlib module
from pathlib import PurePath
# Path
path = '/Desktop/file.txt'
# Instantiate the PurePath class
obj = PurePath(path)
# Get the final path component
comp = obj.name
print(comp)
Concrete Paths:
Concrete Paths refer to classes that provide methods for performing operations on the filesystem. These paths are “concrete” because they interact with the actual filesystem, allowing for the execution of file and directory operations such as checking existence, making directories, reading files and more. We can instantiate a concrete path in following three ways:
class pathlib.Path(*pathsegments) :
It represents a path and allows for a variety of methods that interact directly with the filesystem. Depending on the system Python is running on, Path will behave like either PosixPath or WindowsPath.
Python
# Import the Path class
from pathlib import Path
# Instantiate the Path class
obj = Path('/usr/local/bin')
print(obj)
OutputPosixPath('/usr/local/bin')
class pathlib.PosixPath(*pathsegments) :
This class is used specifically in UNIX-like systems (Linux, macOS). It inherits all methods from Path and PurePosixPath. It provides methods for UNIX-specific filesystem interaction.
Note: We can not instantiate pathlib.Posixpath class on Windows operating system.
Python
# Import PosixPath class
# from pathlib module
from pathlib import PosixPath
# Instantiate the PosixPath class
obj = PosixPath('/usr/local/bin')
# Print the instance of PosixPath class
print(obj)
OutputPosixPath('/usr/local/bin')
class pathlib.WindowsPath(*pathsegments) :
This class is used on Windows systems. It inherits from Path and PureWindowsPath, adapting path operations to Windows standards. This includes handling paths with drive letters and backslashes.
Python
# Import WindowsPath class
# from pathlib module
from pathlib import WindowsPath
# Instantiate the WindowsPath class
obj = WindowsPath('C:/Program Files/')
# Print the instance of WindowsPath class
print(obj)
OutputWindowsPath('c:/Program Files/')
Below are few methods provided by Path class:
Path.cwd() method :
This method returns a new path object which represents the current working directory. For instance, calling Path.cwd() will give us the path from where your Python script is executed.
Python
# Import Path class
from pathlib import Path
# Get the current working directory name
dir = Path.cwd()
print(dir)
Path.exists() method
:
Path.exists() checks whether the specified path exists on the disk. It returns True if the path exists, otherwise False.
Python
# Import Path class
from pathlib import Path
# Path
path = '/home/hrithik/Desktop'
# Instantiate the Path class
obj = Path(path)
# Check if path points to
# an existing file or directory
print(obj.exists())
Path.is_dir() method
:
This method is used to determine if the path points to a directory. It returns True if the path is a directory, otherwise False.
Python
# Import Path class
from pathlib import Path
# Path
path = '/home/hrithik/Desktop'
# Instantiate the Path class
obj = Path(path)
# Check if path refers to
# directory or not
print(obj.is_dir())
Similar Reads
OS Path module in Python
OS Path module contains some useful functions on pathnames. The path parameters are either strings or bytes. These functions here are used for different purposes such as for merging, normalizing, and retrieving path names in Python. All of these functions accept either only bytes or only string obje
2 min read
Posixpath Module in Python
The posixpath module is a built-in Python module that provides functions for manipulating file paths in a way that adheres to the POSIX standard. This module abstracts the differences in path handling between various operating systems, including Unix-like systems (e.g., Linux, macOS) and Windows. Im
3 min read
PyDictionary module in Python
AyDictionary It's a Python module used to fetch definitions of words, while googletrans provides translation services. meaningstranslationsInstallation To install AyDictionary run the following pip code on the terminal / command prompt: pip install AyDictionary googletrans==4.0.0-rc1Getting Started
1 min read
Python Module Index
Python has a vast ecosystem of modules and packages. These modules enable developers to perform a wide range of tasks without taking the headache of creating a custom module for them to perform a particular task. Whether we have to perform data analysis, set up a web server, or automate tasks, there
4 min read
Python | os.path.join() method
The os.path.join() method is a function in the os module that joins one or more path components intelligently. It constructs a full path by concatenating various components while automatically inserting the appropriate path separator (/ for Unix-based systems and \ for Windows). Example [GFGTABS] Py
4 min read
Python Fire Module
Python Fire is a library to create CLI applications. It can automatically generate command line Interfaces from any object in python. It is not limited to this, it is a good tool for debugging and development purposes. With the help of Fire, you can turn existing code into CLI. In this article, we w
3 min read
Python | os.path.islink() method
OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name man
2 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
7 min read
Python | os.path.dirname() method
OS module in Python provides functions for interacting with the operating system. OS comes under Pythonâs standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name man
2 min read
Python | os.path.ismount() method
os.path module is sub module of Python OS Module in Python used for common path name manipulation. os.path.ismount() method in Python is used to check whether the given path is a mount point or not. A mount point is a point in a file system where a different file system has been mounted. os.path.ism
2 min read