Files, exceptions, and debugging

3.15.2

Read and write files, catch expected failures, and locate errors with tracebacks.

On this page

Use a context manager

with closes the file after the block, including when an exception is raised. Specify an encoding for text you control. Path handles filesystem paths, and encoding matters when a file comes from an external system.

from pathlib import Path

path = Path("orders.txt")
path.write_text("Coffee\nTea\n", encoding="utf-8")
with path.open(encoding="utf-8") as handle:
    orders = handle.read().splitlines()
print(orders)
Example output
['Coffee', 'Tea']

Catch an expected exception

Catch the specific exception you can handle. else runs after a try block that raises no exception. finally runs when control leaves the try statement and is useful for cleanup.

def parse_quantity(text):
    try:
        return int(text)
    except ValueError:
        return None

print(parse_quantity("4"), parse_quantity("ERROR"))
Example output
4 None

Read a traceback

The final line names the error and message. Find the last relevant frame in your own code and inspect the values on that line. For invalid data, decide whether to reject it, report it, or use a documented fallback.

Official references