Reading and Writing Files
open, with, and file modes.
5 minute read
Big idea
open() connects your program to a file. Use it inside a with block, and Python closes the file for you when the block ends — even if something goes wrong.
Writing a file
with open("notes.txt", "w") as f:
f.write("Buy milk\n")
f.write("Call Ada\n")
with open("notes.txt") as f:
print(f.read())output
Buy milk
Call AdaRun and edit it in the app.
open("notes.txt", "w")— open for writing. Creates the file, or empties it if it already exists.as f—fis the open file.f.write(text)— writes text. Unlikeprint, it doesn't add a new line; put\nin yourself.- When the
withblock ends, the file is closed and everything is saved.
File modes
| Mode | Means |
|---|---|
"r" | read (the default) — the file must exist |
"w" | write — create or overwrite |
"a" | append — add to the end, keep what's there |
"x" | create — fail if the file already exists |
Reading line by line
Looping over a file gives one line at a time — the best way to read big files, since only one line is in memory at once:
with open("shopping.txt", "w") as f:
f.write("eggs\nflour\nmilk\n")
with open("shopping.txt", "a") as f:
f.write("sugar\n")
count = 0
with open("shopping.txt") as f:
for line in f:
count += 1
print(count, line.strip())What does it print? Show the answer
1 eggs
2 flour
3 milk
4 sugarRun and edit it in the app.
Each line ends with its \n, which is why .strip() is there — without it, print would add a second line break and you'd see blank lines.
Other ways to read:
f.read()— the whole file as one string.f.readlines()— a list of lines (each still ending in\n).f.read().splitlines()— a list of lines without the\n.
When the file isn't there
with open("missing.txt") as f:
print(f.read())output
No saved notes yetRun and edit it in the app.
Opening a file that doesn't exist for reading raises FileNotFoundError. Wrap it: try: the with block, and except FileNotFoundError: print("No saved notes yet").
Why with?
Without with, you must call f.close() yourself — and if an exception happens first, it never gets called. Unclosed files can lose data that hadn't been saved yet. with makes closing automatic.
notes.txt has 10 lines. What does open("notes.txt", "w") do to it?
Watch it
Think of it like
Borrowing a library book. open checks it out, with is the promise to return it, and the end of the block is the book going back on the shelf — automatically, even if you got distracted.
Key terms
- open() — Opens a file and returns a file object.
- Mode — How the file is opened:
"r","w","a","x". - with — Runs a block and then closes the file automatically.
Check yourself
Why open files in a with block?
Which mode adds to the end of a file?
Does f.write("hi") add a new line?