Browse tutorial categories
On this page

Read a Text File Safely in Python

Use Python's with statement and an explicit encoding to read a text file while ensuring the file is closed reliably.

Python’s pathlib.Path provides a clear way to locate a file. Use a context manager when you need more control over reading, or Path.read_text() for a small file you want in one string.

Read a small file

from pathlib import Path

path = Path("notes.txt")
text = path.read_text(encoding="utf-8")
print(text)

Specifying the encoding avoids relying on the operating system’s default. UTF-8 is a common choice for text files, but match the encoding used when the file was created.

Read one line at a time

For larger files, iterate over the file instead of loading all content into memory:

from pathlib import Path

path = Path("server.log")

with path.open(encoding="utf-8") as file:
    for line_number, line in enumerate(file, start=1):
        print(line_number, line.rstrip("\n"))

The with statement closes the file even when an exception occurs. It also makes resource ownership visible to anyone reading the code.

Handle expected errors

File paths can be wrong, permissions can be missing, and text can use an unexpected encoding. Catch only errors the program can handle meaningfully:

try:
    text = Path("notes.txt").read_text(encoding="utf-8")
except FileNotFoundError:
    print("The notes file was not found.")
except UnicodeDecodeError:
    print("The file is not valid UTF-8 text.")

Avoid silently returning an empty string on failure: it makes missing data appear valid and can hide a problem.

Further reading

For more examples, see the Python documentation for pathlib and open().

#Python#files#encoding