Skip to main content
← Python Study Guide

Code Scholars Tutoring · Python

5.1 Reading and Writing Files

How it works

A context manager opens a file and guarantees it is closed even if an error occurs partway through.

Always open files with a context manager, and read line by line when the file may be large.

Common error

Reading an entire large file into memory when streaming would do.

Worked example

Python

from io import StringIO
with StringIO("red\nblue\n") as source:
    lines = [line.strip() for line in source]
print(lines)

Output

['red', 'blue']

A context manager closes its resource after the block. This in-memory text stream makes the example reproducible; a real file can use open with an explicit encoding and the same reading pattern.

Exercises

5.1.1 · Explain

What can go wrong with opening an existing file in write mode when you intended to add records?

Show solution

Write mode can truncate existing content. Choose the mode deliberately, preserve required data, and test changes on a safe example.

5.1.2 · Write code

Using StringIO, read the numbers on separate lines and print their total.

Show solution

Parse each nonempty line as an integer.

One valid solution

from io import StringIO
with StringIO("4\n7\n") as source:
    total = sum(int(line) for line in source if line.strip())
print(total)

Expected output

11
Open Python compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic