๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ pathlib.html
pathlib โ€” Object-oriented filesystem paths
February 23, 2026 - Source code: Lib/pathlib/ This module offers classes representing filesystem paths with semantics appropriate for different operating systems. Path classes are divided between pure paths, which pro...
๐ŸŒ
Switowski
switowski.com โ€บ blog โ€บ pathlib
Pathlib for Path Manipulations - Sebastian Witowski
If you use too many (Path('//////some/path')), it removes the redundant ones on Linux or Mac, and returns Path('/some/path'). It unifies the API for various file manipulation operations that previously required using different Python modules. You no longer need the glob module to search for files matching a pattern, and you also don't need the os module to get the names of their directories. All this functionality can now be found in the pathlib module (of course, you can still use the os or glob modules, if you prefer).
๐ŸŒ
Real Python
realpython.com โ€บ python-pathlib
Python's pathlib Module: Taming the File System โ€“ Real Python
January 11, 2025 - You can instantiate Path objects using class methods like .cwd(), .home(), or by passing strings to Path. pathlib allows you to read, write, move, and delete files efficiently using methods.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ pathlib-module-in-python
Pathlib Module in Python - GeeksforGeeks
2 weeks ago - 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.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_module_pathlib.asp
Python pathlib Module
The pathlib module provides classes that represent filesystem paths as objects.
๐ŸŒ
Readthedocs
pathlib.readthedocs.io
pathlib โ€” pathlib 1.0.1 documentation
The maintenance repository for this standalone backport module can be found on BitBucket, but activity is expected to be quite low: https://bitbucket.org/pitrou/pathlib/ This module offers classes representing filesystem paths with semantics appropriate for different operating systems.
๐ŸŒ
Medium
dzdata.medium.com โ€บ pathlib-a-better-way-to-work-with-paths-in-python-4f24dea14fab
pathlib โ€” a Better Way to Work with Paths in Python | by DZ | Medium
July 19, 2023 - new_name_path = path_to_my_file.with_stem('new_file') path_to_my_file.rename(new_name_path) ... The pathlib module is a powerful tool to handle paths, files, and directories.
๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ comprehensive-tutorial-on-using-pathlib-in-python-for-file-system-manipulation
How to Use Python's Pathlib (with Examples) | DataCamp
May 22, 2024 - Just like a physical address has ... be broken down into smaller components. pathlib allows us to access and manipulate these components using path attributes through dot notation....
Find elsewhere
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ how-to-use-the-pathlib-module-to-manipulate-filesystem-paths-in-python-3
How To Use the pathlib Module to Manipulate Filesystem Paths in Python 3 | DigitalOcean
July 15, 2020 - Python 3 includes the pathlib module for manipulating file system paths agnostically whatever the operating system. pathlib is similar to the os.path module,โ€ฆ
Top answer
1 of 3
112

pathlib is the more modern way since Python 3.4. The documentation for pathlib says that "For low-level path manipulation on strings, you can also use the os.path module."

It doesn't make much difference for joining paths, but other path commands are more convenient with pathlib compared to os.path. For example, to get the "stem" (filename without extension):

os.path: splitext(basename(path))[0]

pathlib: path.stem

Also, you can use the same type of syntax (commas instead of slashes) to join paths with pathlib as well:

path_2 = Path("/home", "test", "test.txt")

2 of 3
3

os.path is string-based while pathlib is object oriented

os.path operates on strings while pathlib is object-oriented. So if "/home/test/test.txt" is the absolute path (in POSIX format) to access to the file test.txt in the directory /home/test/, the commands:

from os import path

path_1 = path.join("/home", "test", "test.txt")

(executed in a Linux system) return in path_1, the string "/home/test/test.txt" (link to os.path.join() documentation.)

On the other hand, the following commands:

from pathlib import Path

path_2 = Path("/home") / "test" / "test.txt"

return an object called path_2 which represents the file.

A function and a method available with the 2 approaches

By the previous initialization, essentially:

  • The string path_1 can be used as argument of other functions of the module os.path. For example, to check if a file exists:

    from os import path
    
    if path.exists(path_1):
        # the file exists
        do stuff
    
  • The object path_2 is an instance of the class pathlib.Path, so with this object it is possible to call all methods of the class Path.

    Furthermore, if path_2 is created on a POSIX compliant system (such as Linux), its type is PosixPath (a subclass of Path), else if path_2 is created on a Windows system, its type is WindowsPath (a subclass of the class Path).

    An example of the methods available on the object path_2 is the exists() method. The snippet of code below shows how it is used:

    from pathlib import Path
    
    if path_2.exists():
        # the file exists
        do stuff
    

Link

See this article to learn about other differences between the two ways of managing paths with Python: Paths in Python: Comparing os.path and pathlib modules

๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
How to Use pathlib in Python | note.nkmk.me
February 9, 2024 - In Python, the pathlib module allows you to manipulate file and directory (folder) paths as objects. You can perform various operations, such as extracting file names, obtaining path lists, and creati ...
๐ŸŒ
YouTube
youtube.com โ€บ corey schafer
Python Tutorial: Pathlib - The Modern Way to Handle File Paths - YouTube
In this Python Programming video, we will be learning how to use the Pathlib module and see why it's now preferred over os.path.Thank You to the sponsor, Eks...
Published ย  September 23, 2024
Views ย  21K
Top answer
1 of 4
334

Use resolve()

Simply use Path.resolve() like this:

p = p.resolve()

This makes your path absolute and replaces all relative parts with absolute parts, and all symbolic links with physical paths. On case-insensitive file systems, it will also canonicalize the case (file.TXT becomes file.txt).

Avoid absolute() before Python 3.11

The alternative method absolute() was not documented or tested before Python 3.11 (See the discussion in the bug report created by @Jim Fasarakis Hilliard).

Fixes were merged in January 2022.

The difference

The difference between resolve and absolute is that absolute() does not replace the symbolically linked (symlink) parts of the path, and it never raises FileNotFoundError. It does not modify the case either.

If you want to avoid resolve() (e.g. you want to retain symlinks, casing, or relative parts) then use this instead on Python <3.11:

p = Path.cwd() / "file.txt"

This works even if the path you are supplying is absolute -- in that case the cwd (current working directory) is ignored.

Beware non-existing file on Windows

If the file does not exist, in Python 3.6 to 3.9 on Windows, resolve() does not prepend the current working directory. See issue 38671, fixed in Python 3.10.

Beware FileNotFoundError

On Python versions predating v3.6, resolve() does raise a FileNotFoundError if the path is not present on disk.

So if there's any risk to that, either check beforehand with p.exists() or try/catch the error.

# check beforehand
if p.exists():
    p = p.resolve()

# or except afterward
try:
    p = p.resolve()
except FileNotFoundError:
    # deal with the missing file here
    pass

If you're dealing with a path that's not on disk, to begin with, and you're not on Python 3.6+, it's best to revert to os.path.abspath(str(p)).

From 3.6 on, resolve() only raises FileNotFoundError if you use the strict argument.

# might raise FileNotFoundError
p = p.resolve(strict=True)

But beware, using strict makes your code incompatible with Python versions predating 3.6 since those don't accept the strict argument.

2 of 4
88

You're looking for the method .absolute, if my understanding is correct, whose documentation states:

>>> print(p.absolute.__doc__)
Return an absolute version of this path.  This function works
        even if the path doesn't point to anything.

        No normalization is done, i.e. all '.' and '..' will be kept along.
        Use resolve() to get the canonical path to a file.

With a test file on my system this returns:

>>> p = pathlib.Path('testfile')
>>> p.absolute()
PosixPath('/home/jim/testfile')

This method seems to be a new, and still, undocumented addition to Path and Path inheritting objects.

Created an issue to document this.

๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-use-pathlib-module-in-python
Python Path โ€“ How to Use the Pathlib Module with Examples
May 10, 2022 - If we print p, we will get the path to the file we are currently in: ... As shown above, Pathlib creates a path to this file by putting this particular script in a Path object.
๐ŸŒ
Readthedocs
autoclasstoc.readthedocs.io โ€บ en โ€บ latest โ€บ examples โ€บ pathlib.html
pathlib.Path โ€” autoclasstoc 1.7.0 documentation
Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object.
๐ŸŒ
ZetCode
zetcode.com โ€บ python โ€บ pathlib
Python pathlib - working with files and directories in Python with pathlib
The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ pathlib-module
Python's pathlib module - Python Morsels
November 18, 2024 - Python's pathlib module is the tool to use for working with file paths. See pathlib quick reference tables and examples.
๐ŸŒ
Practical Business Python
pbpython.com โ€บ pathlib-intro.html
Using Pythonโ€™s Pathlib Module - Practical Business Python
November 27, 2017 - To get the examples started, create the Path to the data_analysis directory: from pathlib import Path dir_to_scan = "/media/chris/KINGSTON/data_analysis" p = Path(dir_to_scan)
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ pathlib
pathlib ยท PyPI
Embodies the semantics of different path types. For example, comparing Windows paths ignores casing. Well-defined semantics, eliminating any warts or ambiguities (forward vs. backward slashes, etc.). Python 3.2 or later is recommended, but pathlib is also usable with Python 2.7 and 2.6.
      ยป pip install pathlib
    
Published ย  Sep 03, 2014
Version ย  1.0.1