Open In App

Pathlib module in Python

Last Updated : 19 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Pathlib-module-classes-relation-diagram

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
from pathlib import Path

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)

Output
foo/bar

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)

Output
foo/bar

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)

Output
foo\bar

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())  

Output
True
False

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)

Output
file.txt

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)

Output
PosixPath('/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)

Output
PosixPath('/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)

Output
WindowsPath('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)

Output
/home/ihritik

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())

Output
True

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())

Output
True


Next Article
Practice Tags :

Similar Reads