Read and Write a File in Python: open, with, Modes and Encoding
Make your data outlive the program: write notes.txt with open and with, read it back three ways, see how w wipes a file and a appends, why encoding matters, and what to do when a file isn't there.
What you will learn
- Open a file with with open() and know it closes for you
- Choose the right mode: r reads, w starts fresh, a adds to the end
- Read a file with read(), readlines() or a for loop
- Use encoding="utf-8", handle FileNotFoundError, and understand relative paths
Before you start
- Python basics: strings, lists and loops
- try and except basics
Right now your program keeps its data in variables, and when the program ends all of that is gone. A file is more like a notebook on a shelf. The program ends, and the notebook's still there. You use it the same way every time: take it down, read or write, put it back. In Python that's open, do the work, close.
Writing a file
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("Buy milk\n")
f.write("Call Sam\n")
print("saved")
saved
open takes three things here:
- The file name,
notes.txt. - The mode, which says what you want to do.
"w"is write,"r"is read, and"a"adds to the end. encoding="utf-8", which we'll come back to.
open hands you a file object, and as f gives it a short name. f.write puts text in the file. The \n is the new line; write doesn't add one for you. When the indented block ends, with closes the file, so you can't forget, even if something goes wrong inside the block. After the run, notes.txt appears in the project. It wasn't there before, so w created it.
Reading it back
with open("notes.txt", "r", encoding="utf-8") as f:
text = f.read()
print(text)
print(len(text))
Buy milk
Call Sam
18
f.read() takes the whole file and gives you one string. The blank line appears because the text already ends with a new line and print adds one more. The length is 18: each line has nine characters, because the new line counts as one.
Is the file really closed?
with open("notes.txt", encoding="utf-8") as f:
text = f.read()
print(f.closed)
print(text)
True
Buy milk
Call Sam
"r" is the default mode, so you can leave it out. Outside the block, f.closed is True, but text still has the two lines because it's an ordinary string in memory now. Do the file work inside the block and use the result anywhere.
Three ways to read
Sometimes you want a list, one item per line:
with open("notes.txt", encoding="utf-8") as f:
lines = f.readlines()
print(lines)
print(len(lines))
['Buy milk\n', 'Call Sam\n']
2
Each item still has its \n. Most of the time you don't need the whole file at once. The file object goes straight into a for loop:
with open("notes.txt", encoding="utf-8") as f:
for line in f:
print("Task:", line.strip())
Task: Buy milk
Task: Call Sam
strip() takes the new line off each one. Python reads one line each time round, so this is the normal way to go through a file, and it works the same on a file far bigger than memory.
| Call | Gives you |
|---|---|
f.read() | the whole file as one string |
f.readlines() | a list, one string per line, each ending in \n |
for line in f | one line at a time |
Always say encoding="utf-8"
A file only stores bytes, so Python needs a rule to turn text into bytes and back. That rule is the encoding.
with open("menu.txt", "w", encoding="utf-8") as f:
f.write("café\n")
with open("menu.txt", encoding="utf-8") as f:
line = f.read().strip()
print(line)
print(len(line))
café
4
Reading with the same encoding gives you the same word back, and its length is 4 characters. If you leave the encoding out, Python uses your computer's default, and that can differ from one machine to another. For text files, always write encoding="utf-8". It saves you from strange characters later.
w starts fresh, a adds to the end
with open("log.txt", "w", encoding="utf-8") as f:
f.write("one\n")
f.write("two\n")
with open("log.txt", "w", encoding="utf-8") as f:
f.write("three\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read(), end="")
three
The moment the second open with "w" runs, the old content is gone, before anything is written. If the file holds something you need, w isn't the mode you want. To keep what's there, use "a":
with open("log.txt", "a", encoding="utf-8") as f:
f.write("four\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read(), end="")
three
four
That's what you want for logs and notes.
When the file isn't there
with open("missing.txt", encoding="utf-8") as f:
print(f.read())
print("Done")
Traceback (most recent call last):
File "S04L00_2_Files\missing_file.py", line 1, in <module>
with open("missing.txt", encoding="utf-8") as f:
~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
You already have the fix from try and except basics. Put the whole with block inside try:
try:
with open("missing.txt", encoding="utf-8") as f:
print(f.read())
except FileNotFoundError:
print("No such file yet")
print("Done")
No such file yet
Done
The program carries on, and reading doesn't create a file.
Where Python looks: relative paths
Just notes.txt is a relative path. It's relative to the folder the program is running from, the working directory.
import os
print(os.path.exists("notes.txt"))
True
Run from the project folder, it prints True. Move into a folder called elsewhere, one level down, and run the same file from there: it prints False. Same code, same name, but Python is looking in a different folder. If a file you can see gives you "not found", check which folder you're running from. The next step, context managers and pathlib, builds paths that don't depend on that.
Quick recap
with open(...) as fgives you a file and closes it for you.rreads,wstarts fresh (wipes it),aadds to the end.read()gives one string,readlines()a list, aforloop one line at a time.- Use
encoding="utf-8", and catchFileNotFoundErrorwhen a file might not be there.
Try it yourself
Open notes.txt in a mode, add the line "Pay rent", then read the file back and print every line. You should see three lines:
Buy milk
Call Sam
Pay rentRelated course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Set Up a Python AI Project with uv, VS Code and an API Key in .env
One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.
uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
One tool instead of venv, activate, pip install and pip freeze. Build a small chatbot project with uv init, hit ModuleNotFoundError, fix it with uv add, read pyproject.toml and uv.lock, then delete .venv and rebuild it with uv sync.
Python try and except Basics: Catch an Error and Keep Going
An exception is the object Python creates when something goes wrong. Catch it with try and a named except, read it with as, add else and finally, retry bad input in a loop, and see why a bare except hides your bugs.
Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
raise sends an error and except receives it. Follow an error up the call stack, use the exception family tree, re-raise and chain errors with raise from, and build InsufficientFundsError and an AppError family of your own.
