Lesson 1 of 9
Everything you've written so far vanishes when the program ends. Files change that — they're how data survives.
The open() function gives you a file object to work with.
with open("notes.txt", "w") as f:
f.write("Line one\nLine two\nLine three\n")
f = open("notes.txt")
content = f.read()
f.close()
print(content)
(The first block creates a file to read — writing is properly covered in the next lesson.)
open() takes a filename and returns a file object. .read() returns the whole contents as one
string. .close() releases the file.
Modes
The second argument sets the mode:
| Mode | Meaning |
| --- | --- |
| "r" | read (the default) — errors if the file is missing |
| "w" | write — creates or completely overwrites |
| "a" | append — adds to the end |
| "x" | create — errors if the file already exists |
open("notes.txt") and open("notes.txt", "r") are the same thing.
Three ways to read
.read() gives you everything as one string:
with open("data.txt", "w") as f:
f.write("apple\nbanana\ncherry\n")
with open("data.txt") as f:
print(f.read())
.readlines() gives you a list, one item per line — note each still carries its \n:
with open("data.txt", "w") as f:
f.write("apple\nbanana\ncherry\n")
with open("data.txt") as f:
lines = f.readlines()
print(lines)
print(len(lines))
Looping over the file gives one line at a time, and is the best option for large files because it never loads the whole thing into memory:
with open("data.txt", "w") as f:
f.write("apple\nbanana\ncherry\n")
with open("data.txt") as f:
for line in f:
print(line.strip())
.strip() removes the trailing newline — without it you'd get a blank line between each.
A file can only be read once
The file object tracks a position. Once you reach the end, there's nothing left:
with open("data.txt", "w") as f:
f.write("hello\n")
with open("data.txt") as f:
print(repr(f.read()))
print(repr(f.read()))
The second .read() returns an empty string. Store the contents in a variable if you need them
twice.
Missing files
Reading a file that doesn't exist raises FileNotFoundError:
f = open("nope.txt")
Lesson 6.6 shows how to handle that gracefully instead of crashing.
Try it yourself
Write three lines, then read them back both as one string and as a list.
Checkpoint
open(path, mode)returns a file object;"r"is the default mode..read()gives one string,.readlines()a list, looping gives line by line.- Lines keep their trailing
\n— use.strip(). - A file object can only be read through once.
- A missing file raises
FileNotFoundError.
Questions about this lesson
Log in to ask a question.