Skip to content
    geeksforgeeks
    • Interview Prep
      • DSA
      • Interview Corner
      • Aptitude & Reasoning
      • Practice Coding Problems
      • All Courses
    • Tutorials
      • Python
      • Java
      • ML & Data Science
      • Programming Languages
      • Web Development
      • CS Subjects
      • DevOps
      • Software and Tools
      • School Learning
    • Tracks
      • Languages
        • Python
        • C
        • C++
        • Java
        • Advanced Java
        • SQL
        • JavaScript
        • C#
      • Interview Preparation
        • GfG 160
        • GfG 360
        • System Design
        • Core Subjects
        • Interview Questions
        • Interview Puzzles
        • Aptitude and Reasoning
        • Product Management
        • Computer Organisation and Architecture
      • Data Science
        • Python
        • Data Analytics
        • Complete Data Science
        • Gen AI
        • Agentic AI
      • Dev Skills
        • Full-Stack Web Dev
        • DevOps
        • Software Testing
        • CyberSecurity
        • NextJS
        • Git
      • Tools
        • Computer Fundamentals
        • AI Tools
        • MS Excel & Google Sheets
        • MS Word & Google Docs
      • Maths
        • Maths For Computer Science
        • Engineering Mathematics
        • School Maths
    • Python Tutorial
    • Data Types
    • Interview Questions
    • Examples
    • Quizzes
    • DSA Python
    • Data Science
    • NumPy
    • Pandas
    • Practice
    • Django
    • Flask
    • Projects
    Open In App

    Pathlib module in Python

    Last Updated : 08 Sep, 2025
    Comments
    Improve
    Suggest changes
    5 Likes
    Like
    Report

    The pathlib module in Python (introduced in version 3.4) provides an object-oriented way to work with filesystem paths. Unlike traditional os.path which treats paths as plain strings, pathlib represents them as objects, making operations like path joining, file reading/writing and checking existence much cleaner and cross-platform.

    Path class in pathlib module is the main class used to represent and interact with file and directory paths on the actual file system.

    Why do we need Pathlib module?

    • Provides an object-oriented alternative to os.path and string-based file handling.
    • Cross-platform compatibility: same code works on Windows, Linux, macOS.
    • Simplifies common tasks like file reading, writing and directory traversal.
    • Safer operations: avoids manual string concatenation by offering methods and operator overloading (/).

    Importing Path Class

    To begin using pathlib, import the Path class:

    from pathlib import Path

    Common File and Directory Operations

    The pathlib module simplifies everyday tasks like listing folders, checking file details and reading or writing files. Let’s explore some examples.

    Listing Subdirectories

    To view all subdirectories within a given directory, use iterdir() method and filter results using .is_dir(). This helps you easily identify folders without scanning files.

    Example: This code lists all subdirectories inside root (/ on Linux or C:/ on Windows).

    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
    /tmp
    /usr
    /etc
    /boot
    /proc
    /dev
    /srv
    /lib
    

    Explanation:

    • Path('/'): Creates a Path object pointing to root directory (/ in Unix/Linux or C:/ in Windows).
    • iterdir(): Returns all immediate entries (files and directories) in path p.
    • is_dir(): Checks if the current entry is a directory (ignores files).

    Listing Python Source Files in This Directory Tree

    To find all Python files (.py) within a folder and its subfolders, use rglob() method from pathlib. It performs a recursive search, making it easy to scan entire directory trees for specific file types.

    Example: This code recursively searches for all .py files in the root directory.

    Python
    from pathlib import Path
    p = Path('/')
    files = p.rglob('*.py')
    for f in files:
        print(f)
    

    Output

    \ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\abc.py
    \ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\aifc.py
    \ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\antigravity.py
    \ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2288.0_x64__qbz5n2kfra8p0\Lib\argparse.py

    Explanation: Here, unlike iterdir() which lists only immediate contents, rglob(*.py) recursively finds all .py files under the directory tree.

    Navigating Inside a Directory Tree

    pathlib makes directory navigation simple by overloading / operator. This allows you to join paths cleanly and create new Path objects without using manual string concatenation.

    Example: This code joins an existing path with "example.txt" to create a new path object.

    Python
    sp = p / 'example.txt'
    print(sp)
    

    Output

    \example.txt

    Explanation:

    • / operator: Overloaded by pathlib to join paths in an object-oriented way.
    • p / 'example.txt': Creates a new Path object by joining p (a directory) with 'example.txt'

    Note: The exact output depends on your operating system (/example.txt on Linux/macOS, \example.txt on Windows).

    Querying Path Properties

    The pathlib module makes it easy to inspect various properties of a file or directory path, such as whether it's absolute, its name, extension, parent directory, etc all using simple methods.

    Example: This code checks whether the path is absolute, retrieves the file name, extension and parent directory.

    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

    pathlib makes file handling easy by allowing you to open, read and write files directly through Path objects no need for manual path strings or separate functions.

    Example: This code reads content from example.txt and writes "Hello, GFG!" into output.txt.

    Python
    # Reading from a file
    with (p / 'example.txt').open('r') as file:
        content = file.read()
        print(content)
    
    # Writing to a file
    with (p / 'output.txt').open('w') as file:
        file.write("Hello, GFG!")
    

    Output

    First line of text.
    Second line of text.
    Third line of text.

    Explanation:

    • open('r') opens file in read mode and open('w') opens file in write mode (creates or overwrites).
    • read() reads file's content and write() writes text to file.

    Hierarchy of Path Classes in pathlib Module

    purepath
    Representation of relation between various classes of pathlib module

    Types of Pathlib module

    Path classes in pathlib module are divided into Pure paths and Concrete paths. Let's discuss it clearly with examples.

    Pure Paths

    Pure path classes perform only path manipulations without touching the file system. They are useful for cross-platform string-based path handling (join, split, normalize).

    PurePaths can be instantiated in following ways using:

    1. PurePath class:

    It allows you to work with and manipulate path strings. When instantiated, it automatically returns a PurePosixPath or PureWindowsPath based on operating system, making it ideal for cross-platform path handling.

    Example: This code imports PurePath class and creates a path object using PurePath('foo/bar') which represents path as a string. Then print() function displays resulting path object.

    Python
    from pathlib import PurePath
    obj = PurePath('foo/bar') # Instantiate PurePath class
    print(obj) 
    

    Output
    foo/bar
    

    2. PurePosixPath class:

    This class from pathlib module represents UNIX-style paths (used in Linux and macOS). It is meant for systems that use forward slashes / and should not be used on Windows.

    Example: This code imports PurePosixPath class and creates a UNIX-style path object using PurePosixPath('foo/bar'), which represents given path purely as a string.

    Python
    from pathlib import PurePosixPath
    obj = PurePosixPath('foo/bar') # Instantiate PurePosixPath class
    print(obj)
    

    Output
    foo/bar
    

    3. PureWindowsPath class:

    This class is used to handle Windows-style file system paths. PureWindowsPath understands Windows path conventions (like backslashes and drive letters), making it useful for creating or manipulating Windows paths even on non-Windows systems.

    Example: This code imports PureWindowsPath class and creates a path object using PureWindowsPath('foo/bar'), print() function displays resulting path object using backslashes (\) as per Windows path conventions.

    Python
    from pathlib import PureWindowsPath
    obj = PureWindowsPath('foo/bar') # Instantiate PureWindowsPath class
    print(obj)
    

    Output
    foo\bar
    

    Concrete Paths

    Concrete path classes interact with actual file system and support both path manipulations and file I/O operations. They provide methods for reading, writing, checking file existence, creating directories, etc.

    We can instantiate a concrete path in following ways using:

    1. Path class:

    It represents a path and allows for a variety of methods that interact directly with the filesystem. Depending on system Python is running on, Path will behave like either PosixPath or WindowsPath.

    Example: This code imports Path and creates a concrete path object using Path('/usr/local/bin'), which represents a real path in file system. The print() function displays resulting Path object.

    Python
    from pathlib import Path
    obj = Path('/usr/local/bin') # Instantiate Path class
    print(obj)
    

    Output
    /usr/local/bin
    

    2. PosixPath class:

    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.

    Example: This code imports PosixPath class and creates a concrete path object using PosixPath('/usr/local/bin') which represents a Unix-style file system path.

    Python
    from pathlib import PosixPath
    obj = PosixPath('/usr/local/bin') # Instantiate PosixPath class
    print(obj)
    

    Output
    /usr/local/bin
    

    3. WindowsPath class:

    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.

    Example: This code imports WindowsPath class and creates a concrete path object using WindowsPath('C:/Program Files/') which represents a Windows-style file system path.

    Python
    from pathlib import WindowsPath
    obj = WindowsPath('C:/Program Files/') # Instantiate WindowsPath class
    print(obj)
    

    Output
    WindowsPath('c:/Program Files/')
    

    Below are few methods provided by Path class:

    1. cwd() method:

    This method returns a new path object which represents current working directory. For instance, calling Path.cwd() will give us path from where your Python script is executed.

    Example: This code gets the current working directory where the Python script is executed.

    Python
    from pathlib import Path
    dir = Path.cwd()
    print(dir)
    

    Output
    /home/guest/sandbox
    

    2. exists() method:

    It checks whether specified path exists on the disk. It returns True if the path exists, otherwise False.

    Example: This code checks whether the given path exists.

    Python
    from pathlib import Path
    path = '/home/hrithik/Desktop'
    obj = Path(path) # Create Path object
    print(obj.exists())
    

    Output
    True
    

    3. is_dir() method:

    This method is used to determine if path points to a directory. It returns True if the path is a directory, otherwise False.

    Example: This code checks whether the given path is a directory.

    Python
    from pathlib import Path
    path = '/home/hrithik/Desktop'
    obj = Path(path) # Instantiate the Path class
    print(obj.is_dir()) 
    

    Output
    True
    
    Create Quiz

    I

    ihritik
    Improve

    I

    ihritik
    Improve
    Article Tags :
    • Python
    • python-utility
    • python-modules

    Explore

      Python Fundamentals

      Python Introduction

      2 min read

      Input and Output in Python

      4 min read

      Python Variables

      4 min read

      Python Operators

      4 min read

      Python Keywords

      2 min read

      Python Data Types

      8 min read

      Conditional Statements in Python

      3 min read

      Loops in Python - For, While and Nested Loops

      5 min read

      Python Functions

      5 min read

      Recursion in Python

      4 min read

      Python Lambda Functions

      5 min read

      Python Data Structures

      Python String

      5 min read

      Python Lists

      4 min read

      Python Tuples

      4 min read

      Python Dictionary

      3 min read

      Python Sets

      6 min read

      Python Arrays

      7 min read

      List Comprehension in Python

      4 min read

      Advanced Python

      Python OOP Concepts

      11 min read

      Python Exception Handling

      5 min read

      File Handling in Python

      4 min read

      Python Database Tutorial

      4 min read

      Python MongoDB Tutorial

      3 min read

      Python MySQL

      9 min read

      Python Packages

      10 min read

      Python Modules

      3 min read

      Python DSA Libraries

      15 min read

      List of Python GUI Library and Packages

      3 min read

      Data Science with Python

      NumPy Tutorial - Python Library

      3 min read

      Pandas Tutorial

      4 min read

      Matplotlib Tutorial

      5 min read

      Python Seaborn Tutorial

      3 min read

      StatsModel Library - Tutorial

      3 min read

      Learning Model Building in Scikit-learn

      6 min read

      TensorFlow Tutorial

      2 min read

      PyTorch Tutorial

      6 min read

      Web Development with Python

      Flask Tutorial

      8 min read

      Django Tutorial | Learn Django Framework

      7 min read

      Django ORM - Inserting, Updating & Deleting Data

      4 min read

      Templating With Jinja2 in Flask

      6 min read

      Django Templates

      5 min read

      Build a REST API using Flask - Python

      3 min read

      Building a Simple API with Django REST Framework

      3 min read

      Python Practice

      Python Quiz

      1 min read

      Python Coding Practice

      1 min read

      Python Interview Questions and Answers

      15+ min read
    top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Campus Training Program
  • Explore
  • POTD
  • Job-A-Thon
  • Blogs
  • Nation Skill Up
  • Tutorials
  • Programming Languages
  • DSA
  • Web Technology
  • AI, ML & Data Science
  • DevOps
  • CS Core Subjects
  • Interview Preparation
  • Software and Tools
  • Courses
  • ML and Data Science
  • DSA and Placements
  • Web Development
  • Programming Languages
  • DevOps & Cloud
  • GATE
  • Trending Technologies
  • Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
  • Preparation Corner
  • Interview Corner
  • Aptitude
  • Puzzles
  • GfG 160
  • System Design
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.
See More

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences