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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read