← Python course

Lesson 08

Reading and writing files

Making data outlive the program that created it.

Everything so far disappears the moment your program ends. Files are how programs remember things between runs.

Loading editor…

open("notes.txt", "w") opens a file for writing (creating it if it doesn't exist, erasing it if it does). open("notes.txt", "r") opens it for reading. The with ... as file: wrapper makes sure the file is properly closed when you're done with it — always use it.

\n inside a string is a newline character — it doesn't print as text, it moves to the next line.

You can also build up the file line by line from a list:

Loading editor…

.strip() removes extra whitespace — useful because reading a file line by line keeps the \n at the end unless you strip it off.

A practical pattern: append instead of overwrite, using "a" mode, so a log file grows instead of getting wiped each run:

Loading editor…

Run that cell a few times and watch the log grow — each run adds a line instead of replacing the file.

Your turn

Write a small list of your own (favorite movies, games, whatever) to a file, one per line, then read it back and print each one with a number in front.

Loading editor…

Next lesson: pandas — handling real, messy data like a spreadsheet, in code.