HomeGuidesPythonPython File I/O Explained — open(), read, write & Context Managers
🐍 Python

Python File I/O: Reading, Writing, and Context Managers

File I/O is straightforward once you know the patterns. Here's what exams test — file modes, reading methods, and the with statement.

Examifyr·2026·5 min read

Opening files with open()

The built-in open() function takes a filename and mode. Always use a context manager.

# Basic (manual close — risky)
f = open("data.txt", "r")
content = f.read()
f.close()

# Better: context manager
with open("data.txt", "r") as f:
    content = f.read()
# File is automatically closed here
Note: Using the with statement guarantees the file is closed, even if an exception occurs. This is the correct way in modern Python.

File modes

The second argument to open() is the mode.

open("file.txt", "r")   # read (default)
open("file.txt", "w")   # write (creates/overwrites)
open("file.txt", "a")   # append (adds to end)
open("file.txt", "x")   # exclusive create (fails if exists)
open("file.txt", "rb")  # read binary
open("file.txt", "r+")  # read and write
Note: "w" mode OVERWRITES an existing file. Use "a" to add to an existing file.

Reading from files

There are three ways to read. Choose based on whether you want everything at once or line by line.

with open("data.txt", "r") as f:
    content = f.read()           # entire file as string

with open("data.txt", "r") as f:
    lines = f.readlines()        # list of lines (with \n)

# Most Pythonic — memory-efficient:
with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())      # strip removes trailing \n

Writing to files

write() writes a string. writelines() writes a list of strings. Neither adds newlines automatically.

with open("output.txt", "w") as f:
    f.write("First line\n")
    f.write("Second line\n")

lines = ["line 1\n", "line 2\n"]
with open("output.txt", "w") as f:
    f.writelines(lines)

with open("log.txt", "a") as f:
    f.write("New entry\n")
Note: write() and writelines() don't add newlines automatically. Include \n in your strings.

Working with JSON files

JSON is the most common file format in Python exams and real-world code.

import json

data = {"name": "Alice", "score": 95}
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

with open("data.json", "r") as f:
    loaded = json.load(f)

# String conversion (no file):
json_str = json.dumps(data)   # dict → string
back = json.loads(json_str)   # string → dict

Exam tip

The most common file I/O exam question involves the "w" mode overwriting an existing file (vs "a" for append). Also know that iterating over a file object directly (`for line in f`) is more memory-efficient than f.readlines().

🎯

Think you're ready? Prove it.

Take the free Python readiness test. Get a score, topic breakdown, and your exact weak areas.

Take the free Python test →

Free · No sign-up · Instant results

← Previous
Python Modules and Imports Explained — import, from, __name__
← All Python guides