Unit 09 · lesson

Reading and Writing Files

Core path: 30 minutes

What changes when data has to survive after the Python process stops?

Up to this point, most of your program state has lived only in memory.

score = 950

While the process is running, score exists.

Stop the process and start the program again. Unless you deliberately saved that value somewhere persistent, the new process does not inherit the old variable.

Files give the program a way to move data across that shutdown boundary.

A file operation crosses from memory to disk

Consider:

file = open("message.txt", "r")
contents = file.read()
print(contents)
file.close()

Several things happen:

Python process
    ↓ asks operating system to open
message.txt on disk
    ↓ bytes/text are read
contents in memory

print displays the value

The file and the variable are not the same copy of the data.

The file exists on storage.

contents exists in the running process after reading.

That separation becomes very important once programs modify data and save it later.

Use with so cleanup has a clear boundary

The manual version works when everything goes normally:

file = open("message.txt", "r")
contents = file.read()
file.close()

But it makes you responsible for closing the file correctly across every path.

Prefer:

with open("message.txt", "r") as file:
    contents = file.read()

print(contents)

The with block gives the file resource a defined lifetime. Python's context-manager protocol handles the cleanup when the block exits, including many exception paths.

You do not need to memorize the phrase context manager and move on. Understand the job:

acquire a resource, use it inside a controlled block, release it when the block ends.

You will see the same pattern with other resources later.

File modes change the meaning of the operation

ModeWhat the program is asking for
"r"read an existing file
"w"write a new contents state, replacing the old file contents if the file exists
"a"append new content to the end

The dangerous misconception is:

w means "write something."

More precisely, it opens the file for writing in a way that normally truncates existing contents.

That can destroy data you meant to preserve.

Prove the difference between write and append

Start with:

status.log

containing:

BOOT

Run:

with open("status.log", "a") as file:
    file.write("ONLINE\n")

The file should become:

BOOT
ONLINE

Now run:

with open("status.log", "w") as file:
    file.write("RESET\n")

Inspect the file again.

Now it contains:

RESET

That is not a Python failure. The w mode did what you asked.

Newlines are data too

with open("system.log", "a") as file:
    file.write("System started\n")

\n represents a newline character.

Without it:

file.write("System started")
file.write("Battery checked")

can produce:

System startedBattery checked

The file stores exactly the characters you write. Formatting is part of the data representation.

Read line by line when the file itself is line-oriented

with open("systems.txt", "r") as file:
    for line in file:
        print(line.strip())

The file object can be iterated one line at a time.

strip() removes surrounding whitespace, including the newline normally attached to a text line read from the file.

Be careful: strip() can remove more than \n. It removes surrounding whitespace. Use it because that behavior matches your data, not because every file-reading tutorial contains it.

Interactive model

Follow data from memory to disk and back

Persistence is a boundary crossing: Python data becomes file content, survives process exit, then is read and reconstructed later.

Drag nodes to inspect the relationships. Motion shows the active path; the plain background keeps attention on the relationships instead of graph-paper decoration.

View static diagramStatic Python file lifecycle

Read the interactive model as a state lifecycle:

program has data in memory
        ↓ write
file receives representation on disk
        ↓ process can stop
file remains
        ↓ later read
new process reconstructs data in memory

The arrows mean data is being represented across a storage boundary, not that the exact Python variable survives on disk.

Predict the file after two writes

Start with an empty status.txt.

Run:

with open("status.txt", "w") as file:
    file.write("ONLINE\n")

with open("status.txt", "a") as file:
    file.write("BATTERY 82\n")

Predict the exact file contents before opening it.

Expected:

ONLINE
BATTERY 82

Now change the second mode from "a" to "w".

Predict again before running.

Expected final contents:

BATTERY 82

The second write replaced the previous contents.

That one-character mode change changed persistence behavior.

File I/O can fail for reasons outside your calculation logic

Reading a file adds new failure possibilities:

wrong path
missing file
permission problem
unexpected text encoding
malformed data
wrong open mode

Do not automatically translate all of those into "my Python logic is wrong."

The program is now interacting with another layer: the filesystem.

Lesson 2 teaches you to inspect that layer deliberately.

Before moving on

You should be able to explain:

  • the difference between a file on disk and a variable in memory;
  • why with open(...) creates a useful resource boundary;
  • what r, w, and a change;
  • why a missing newline changes text-file output;
  • what state survives after the process stops and what does not.

Vocabulary lab

Flip the idea, not just the card

Explain the term before you reveal the back. Then compare your explanation with the definition, example, and warning.

1 / 5
Read all terms without animation
Persistence
The ability for data to remain available after the process that created or used it stops. Example: Saving a roster to JSON and loading it in a later run. Do not confuse it with: A variable that exists only in runtime memory.
File Mode
The requested file operation behavior used when opening a file. Example: 'a' appends while 'w' normally replaces existing contents. Do not confuse it with: The file path that identifies which file to open.
Append
Add new data to the end of existing file contents. Example: Opening a log with mode 'a' and writing another line. Do not confuse it with: Opening with 'w', which normally replaces the current contents.
Context Manager
A Python protocol used to manage setup and cleanup around a block of work. Example: with open(...) as file manages the file resource across the block. Do not confuse it with: A filename or directory path.
Newline
A character representing a line break in text data. Example: ' ' after a log entry. Do not confuse it with: A visible space character within the same line.