Showing results for pathlib path
Search instead for pathlibpath

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

Answer from wisbucky on Stack Overflow
🌐
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
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).
Discussions

Using Python's pathlib module
In that opening example using open() I don't see why anybody would ever want to pass a Path to open() when paths can be opened natively: from pathlib import Path path = Path("example.txt") with path.open() as file: contents = file.read() More on reddit.com
🌐 r/Python
26
93
November 20, 2024
pathlib.Path vs. os.path.join in Python - Stack Overflow
Personally I don’t like the slash ... os.path.join, but it’s really just a matter of taste. ... As far as functionality goes, both do the same thing. It's mostly a matter of preference which one you like. treyhunner.com/2018/12/why-you-should-be-using-pathlib... More on stackoverflow.com
🌐 stackoverflow.com
What is the obvious way to open a file: open( ) or pathlib/Path?
.read_text() is just fine if you're really ONLY doing a full read of the entire file as a single, large string from a text file. open() gives greater control by allowing you to specify read ('r'), write ('w') or append ('a) and to read line by line, etc, while executing those actions on a much wider variety of file types. For using open() it is recommended to use the 'with' context manager simply because that will take care of closing the file for you when things are all done. More on reddit.com
🌐 r/learnpython
8
9
March 17, 2023
Pathlib and why you should try it.
Well, the first version of yours isn't the recommended way even in Python2. It should be os.path.join("/etc/configDir", "myProgramConfig.cfg") More on reddit.com
🌐 r/learnpython
15
21
March 20, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › python › pathlib-module-in-python
Pathlib module in Python - GeeksforGeeks
September 8, 2025 - 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 (/). ... The pathlib module simplifies everyday tasks like listing folders, checking file details and reading or writing files.
🌐
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.
🌐
W3Schools
w3schools.com › python › ref_module_pathlib.asp
Python pathlib Module
The pathlib module provides classes that represent filesystem paths as objects.
Find elsewhere
🌐
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.
🌐
Trey Hunner
treyhunner.com › 2018 › 12 › why-you-should-be-using-pathlib
Why you should be using pathlib
December 21, 2018 - There’s a lot of lovely stuff ... you’ll need to do a bit of digging. The pathlib module replaces many of these filesystem-related os utilities with methods on the Path object....
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

🌐
Medium
medium.com › @thomas_reid › a-quick-tour-of-the-python-pathlib-library-0ab9c217634e
A quick tour of the Python Pathlib library | by Thomas Reid | Medium
August 15, 2024 - A quick tour of the Python Pathlib library Stop using os (mostly) and use Pathlib instead Before Python version 3.4, when you had to refer to and perform operations on files and directories on your …
🌐
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....
🌐
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.
🌐
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
🌐
Reddit
reddit.com › r/learnpython › what is the obvious way to open a file: open( ) or pathlib/path?
r/learnpython on Reddit: What is the obvious way to open a file: open( ) or pathlib/Path?
March 17, 2023 -

According to the Zen of Python, "there should be one-- and preferably only one --obvious way to do it."

In the book Python Crash Course I learned to use the pathlib module to read and write files:

from pathlib import Path

p = Path("my_file.txt")

contents = p.read_text()

However, the Python documentation uses open( ) instead:

with open("my_file.txt", encoding="utf-8") as f:
    contents = f.read()

What is the best, or "obvious" approach?

Top answer
1 of 4
5
.read_text() is just fine if you're really ONLY doing a full read of the entire file as a single, large string from a text file. open() gives greater control by allowing you to specify read ('r'), write ('w') or append ('a) and to read line by line, etc, while executing those actions on a much wider variety of file types. For using open() it is recommended to use the 'with' context manager simply because that will take care of closing the file for you when things are all done.
2 of 4
5
I say, default to pathlib.Path and its methods, and use open if you Need to pass a file object to something Need to save memory and cannot fit the entire file to it at once Need to append data There may be other cases I didn't immediately think of. Reading and writing all the file contents at once is in my opinion preferable, because by minimising the amount of time the file is kept open, you can alleviate the risk of race conditions - even if you don't use multiprocessing, if the user deletes the file while you're in the middle of reading it, your program might not be designed to handle that. pathlib, in my opinion, should nowadays be treated as the canonical way to handle files. I'd even go as far to say that unless there's a need for supporting older Python versions, pathlib.Path.open is preferable to open (they're basically the same thing, but the path argument is provided by the pathlib.Path instance automatically). The documentation may not always follow the latest trends and recommendations, and there are reasons for that. Hence the discrepancy.
🌐
Python Snacks
pythonsnacks.com › p › paths-in-python-comparing-os-path-and-pathlib
Paths in Python: Comparing os.path and pathlib modules
January 23, 2026 - os.path operates on strings, requiring function calls for every path operation, whereas pathlib takes an object-oriented approach.
🌐
Practical Business Python
pbpython.com › pathlib-intro.html
Using Python’s Pathlib Module - Practical Business Python
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)
🌐
Medium
medium.com › @barila › choose-your-path-pythons-pathlib-vs-os-path-4de0b1e752dd
Choose Your Path: Python’s pathlib vs os.path | by Ori Bar-ilan | Medium
February 13, 2024 - It provides an abstraction over system paths by encapsulating the idea of a path as an object, allowing for more intuitive and readable code. With pathlib, you can perform most path manipulations using methods directly on path objects.
🌐
Stack Abuse
stackabuse.com › introduction-to-the-python-pathlib-module
Introduction to the Python Pathlib Module
August 7, 2023 - Directory represents the filesystem ... deals with path related tasks, such as constructing new paths from names of files and from other paths, checking for various properties of paths and creating files and folders at specific paths....
🌐
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.
🌐
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 ...