.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. Answer from Guideon72 on reddit.com
๐ŸŒ
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...
๐ŸŒ
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.
๐ŸŒ
Real Python
realpython.com โ€บ python-pathlib
Python's pathlib Module: Taming the File System โ€“ Real Python
January 11, 2025 - You can read a file using pathlib by creating a Path object for the file and then calling the .read_text() method to get the fileโ€™s contents as a string. Alternatively, use .open() with a with statement to read the file using traditional file handling techniques.
๐ŸŒ
Readthedocs
pathlib.readthedocs.io
pathlib โ€” pathlib 1.0.1 documentation
>>> p = Path('foo') >>> p.open('w').write('some text') 9 >>> target = Path('bar') >>> p.rename(target) >>> target.open().read() 'some text' ... Rename this file or directory to the given target. If target points to an existing file or directory, it will be unconditionally replaced. This method is only available with Python 3.3; it will raise NotImplementedError on previous Python versions. ... Make the path absolute, resolving any symlinks. A new path object is returned: >>> p = Path() >>> p PosixPath('.') >>> p.resolve() PosixPath('/home/antoine/pathlib')
๐ŸŒ
The Renegade Coder
therenegadecoder.com โ€บ code โ€บ how-to-open-a-file-in-python
How to Open a File in Python: open(), pathlib, and More โ€“ The Renegade Coder
June 10, 2024 - from pathlib import Path my_file = Path('/path/to/file') Then, opening the file is as easy as using the open() method:
๐ŸŒ
Runebook.dev
runebook.dev โ€บ en โ€บ docs โ€บ python โ€บ library โ€บ pathlib โ€บ pathlib.Path.open
python - Handling File Access Errors: A Guide to pathlib.Path.open() Pitfalls
They handle opening, reading/writing, and closing all in one line! from pathlib import Path my_file = Path("hello.txt") # Ensure the file exists for the first run: my_file.write_text("Hello, World!") # Alternative to 'with my_file.open('r') as f: ...' try: content = my_file.read_text(encoding='utf-8') print(f"Read content: {content}") except FileNotFoundError: print("File doesn't exist to read!")
๐ŸŒ
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).
๐ŸŒ
ZetCode
zetcode.com โ€บ python โ€บ pathlib
Python pathlib - working with files and directories in Python with pathlib
The open opens the file pointed to by the path, like the built-in open function does. ... #!/usr/bin/python from pathlib import Path path = Path('words.txt') with path.open() as f: lines = f.readlines() print(lines) for line in lines: print(line.rstrip())
Find elsewhere
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ pathlib-module-in-python
Pathlib Module in Python - GeeksforGeeks
5 days ago - 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. ... from pathlib import WindowsPath obj = WindowsPath('C:/Program Files/') # Instantiate WindowsPath class print(obj)
๐ŸŒ
Python Beginners
python-adv-web-apps.readthedocs.io โ€บ en โ€บ latest โ€บ working_with_files.html
Reading and Writing Files โ€” Python Beginners documentation
Use of the pathlib method .exists(). Files can be opened and read without using Path if they are in the same folder as the Python script.
๐ŸŒ
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 - We can show the unique value of pathlib by considering a common task in data science: how to find all png files inside a given directory and all its sub-directories. If we were using the os module, we might write the following code: import os dir_path = "/home/user/documents" files = [ os.path.join(dir_path, f) for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f)) and f.endswith(".png") ]
Top answer
1 of 3
34

If all you wanted to do was read or write a small blob of text (or bytes), then you no longer need to use a with-statement when using pathlib:

>>> import pathlib
>>> path = pathlib.Path("/tmp/example.txt")
>>> path.write_text("hello world")
11
>>> path.read_text()
'hello world'
>>> path.read_bytes()
b'hello world'

These methods still use a context-manager internally (src).

Opening a large file to iterate lines should still use a with-statement, as the docs show:

>>> with path.open() as f:
...     for line in f:
...         print(line)
...
hello world
2 of 3
7

Keep in mind that a Path object is for working with filesystem paths. Just like the built-in library of Python, there is an open method but no close in a Path object.

The .close is in the file handle that is returned by either the built-in open or by using the Path object's open method:

>>> from pathlib import Path
>>> p=Path(some_file)
>>> p
PosixPath('/tmp/file')

You can open that Path object either with the built-in open function or the open method in the Path object:

>>> fh=open(p)    # open built-in function
>>> fh
<_io.TextIOWrapper name='/tmp/file' mode='r' encoding='UTF-8'>
>>> fh.close()

>>> fh=p.open()   # Path open method which aliases to os.open
>>> fh
<_io.TextIOWrapper name='/tmp/file' mode='r' encoding='UTF-8'>
>>> fh.close()

You can have a look at the source code for pathlib on Github as an indication of how the authors of pathlib do it in their own code.

What I observe is one of three things.

The most common by far is to use with:

from pathlib import Path 

p=Path('/tmp/file')

#create a file
with p.open(mode='w') as fi:
    fi.write(f'Insides of: {str(p)}')

# read it back and test open or closed
with p.open(mode='r') as fi:
    print(f'{fi.read()} closed?:{fi.closed}')

# prints 'Insides of: /tmp/file closed?:False'

As you likely know, at the end of the with block the __exit__ methods are called. For a file, that means the file is closed. This is the most common approach in the pathlib source code.

Second, you can also see in the source that a pathlib object maintains an entry and exit status and a flag of the file being open and closed. The os.close functions is not explicitly called however. You can check that status with the .closed accessor.

fh=p.open()
print(f'{fh.read()} closed?:{fh.closed}')
# prints Insides of: /tmp/file closed?:False    
# fi will only be closed when fi goes out of scope...
# or you could (and should) do fh.close()


with p.open() as fi:
    pass
print(f'closed?:{fi.closed}')   
# fi still in scope but implicitly closed at the end of the with bloc
# prints closed?:True

Third, on cPython, files are closed when the file handle goes out of scope. This is not portable or considered 'good practice' to rely on, but commonly it is. There are instances of this in the pathlib source code.

๐ŸŒ
Python
docs.python.org โ€บ 3.4 โ€บ library โ€บ pathlib.html
11.1. pathlib โ€” Object-oriented filesystem paths โ€” Python 3.4.10 documentation
June 16, 2019 - >>> p = Path('foo') >>> p.open('w').write('some text') 9 >>> target = Path('bar') >>> p.rename(target) >>> target.open().read() 'some text' ... Rename this file or directory to the given target. If target points to an existing file or directory, it will be unconditionally replaced. ... Make the path absolute, resolving any symlinks. A new path object is returned: >>> p = Path() >>> p PosixPath('.') >>> p.resolve() PosixPath('/home/antoine/pathlib')
๐ŸŒ
CodingNomads
codingnomads.com โ€บ python-path-and-pathlib
Python Path and `pathlib`
In previous lessons, you have accessed files using their relative path. An alternate method is to use the absolute path. Python pathlib simplifies this process.
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ pathlib-module
Python's pathlib module - Python Morsels
November 18, 2024 - If you're writing a third-party library that accepts Path objects, use os.fspath instead of str so that any path-like object will be accepted per PEP 519. Unless I'm simply passing a single string to the built-in open function, I pretty much always use pathlib when working with file paths.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ introduction-to-the-python-pathlib-module
Introduction to the Python Pathlib Module
August 7, 2023 - write_text: Used to open the file and writes text and closes it later ยท write_bytes: Used to write binary data to a file and closes the file, once done ยท Let's explore the usage of the Pathlib module for common file operations. The following example is used to read the contents of a file: path = pathlib.Path.cwd() / 'Pathlib.md' path.read_text()
๐ŸŒ
Inspired Python
inspiredpython.com โ€บ tip โ€บ python-pathlib-tips-reading-from-and-writing-to-files
Python Pathlib Tips: Reading from and Writing to Files โ€ข Inspired Python
You can use the pathlib moduleโ€™s Path() class to read and write to files directly, circumventing the need for open() if you donโ€™t need access to the file object.
๐ŸŒ
Trey Hunner
treyhunner.com โ€บ 2018 โ€บ 12 โ€บ why-you-should-be-using-pathlib
Why you should be using pathlib
The pathlib module makes a number of complex cases somewhat simpler, but it also makes some of the simple cases even simpler. ... Or you could use the read_text method on Path objects and a list comprehension to read the file contents into a new list all in one line: ... If you prefer using open, whether as a context manager or otherwise, you could instead use the open method on your Path object:
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-use-pathlib-module-in-python
Python Path โ€“ How to Use the Pathlib Module with Examples
May 10, 2022 - For example, Linux uses forward slashes for paths, while Windows uses backslashes. This small difference can cause issues if you are working on a project and you want other developers who come from different operating systems to expand your code. Fortunately, if you're coding in Python, the Pathlib module does the heavy lifting by letting you make sure that your file paths work the same in different operating systems.
๐ŸŒ
Miguendes
miguendes.me โ€บ python-pathlib
Python pathlib Cookbook: 57+ Examples to Master It (2022)
July 5, 2024 - Python represents JSON objects as plain dictionaries, to write them to a file as JSON using pathlib, we need to combine the json.dump function and Path.open(), the same way we did to read a JSON from disk.