Codectionary / Developer documentation / Python

File Handling

Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.

Before you start: import

Syntax

with open(filepath, mode) as f:\n    # work with f

Breaking down the syntax

with open(...) as file
Keeps the file open inside the block and closes it afterward.
r / w / a
Read, replace contents, or append.
encoding="utf-8"
Specifies the text encoding.

How it works

Open a file to read or write its contents. A with block closes the handle when you leave the block, including when an exception occurs.

Start with a small example

Run the first example, then change one value and predict the result.

Apply the idea

Compare the alternatives below before using this pattern in your own project.

Examples

Write and read a note

Creates its own temporary file and prints Learn Python.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "notes.txt"
    with open(path, "w", encoding="utf-8") as file:
        file.write("Learn Python\n")
    with open(path, "r", encoding="utf-8") as file:
        print(file.read(), end="")
  1. Creates its own temporary file and prints Learn Python.
  2. Writing closes before reading starts.

Append and read lines

Prints 1: Functions and 2: Files on separate lines.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    path = Path(folder) / "topics.txt"
    path.write_text("Functions\n", encoding="utf-8")
    with open(path, "a", encoding="utf-8") as file:
        file.write("Files\n")
    with open(path, encoding="utf-8") as file:
        for number, line in enumerate(file, start=1):
            print(f"{number}: {line.rstrip()}")
  1. Prints 1: Functions and 2: Files on separate lines.
  2. Append preserves the first topic; rstrip removes trailing whitespace for display.

Reading a File

Reading the entire contents of a file at once.

with open("notes.txt", "r") as f:
    content = f.read()

print(content)
# File is automatically closed here, even if an error occurred

Writing to a File

Creating or overwriting a file with new content.

with open("output.txt", "w") as f:
    f.write("Line one\n")
    f.write("Line two\n")

# The file now contains exactly those two lines - any previous content is gone

Appending to a File

Adding new content to the end of an existing file without erasing what's already there.

with open("log.txt", "a") as f:
    f.write("New log entry\n")

# Existing content in log.txt is preserved, new line added at the end

Reading Line by Line

Iterating over a file object processes it one line at a time, which is memory-efficient for large files.

with open("data.csv", "r") as f:
    for line in f:
        print(line.strip())  # .strip() removes the trailing newline

Best practices

  • Always use 'with open(...) as f:' instead of manually calling open() and close() - it guarantees the file closes even if an exception occurs
  • Use mode 'r' for reading, 'w' to overwrite/create, and 'a' to append - mixing these up can accidentally erase data
  • Iterate directly over a file object (for line in f:) rather than reading the whole file into memory when processing large files line by line
  • Specify the encoding explicitly (encoding='utf-8') when working with text files that may contain non-ASCII characters

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

When should I use this?

Read UTF-8 text. Write or append intentionally. Close handles with with.

Common mistakes

Accidentally replacing text

Opening an existing file with w truncates it immediately.

Incorrect

open("notes.txt", "w", encoding="utf-8")

Corrected

with open("notes.txt", "a", encoding="utf-8") as file:
    file.write("Another note\n")

Compare approaches

  • read(): Load a small file into one string.
  • Iterate over the file: Process lines without loading the whole file.
  • JSON: Store structured data.

Explore deeper

Paths and failures

Relative paths start from the current working directory. Handle specific failures such as FileNotFoundError where your application can recover.

Practice files

These examples use TemporaryDirectory, which removes the practice files afterward. For persistent data choose an intentional path outside that temporary context.

Specifications & further reading