Files keep data after a variable is gone.
open() connects your program to a file. Mode r reads, w writes a fresh file and can replace existing content, and a appends new content at the end. Use encoding="utf-8" for predictable text.
with open("orders.txt", "w", encoding="utf-8") as orders:
orders.write("Keyboard x1\n")
with open("orders.txt", "a", encoding="utf-8") as orders:
orders.write("Mouse x2\n")
with open("orders.txt", "r", encoding="utf-8") as orders:
print(orders.read(), end="")with opens the file, gives it the name orders, and closes it when the block ends—even if an exception occurs. write() returns the number of characters written; read() returns all text, while readline() reads one line.
Keyboard x1
Mouse x2Use w only when replacing the record is intended. For another successful order, use a so earlier orders remain. Handle FileNotFoundError when a file may not exist yet.
Browser Playground note: This example uses the Python runtime’s virtual file system in the browser. It is useful for practice, but it is not permanent storage for the learner’s orders.
try:
with open("orders.txt", "r", encoding="utf-8") as orders:
first_order = orders.readline()
print(first_order, end="")
except FileNotFoundError:
print("No orders have been saved yet.")The except block handles only the missing-file case. with still closes a file that was opened successfully.
with open("orders.txt", "w", encoding="utf-8") as orders:
orders.write("New daily record\n")
with open("orders.txt", "a", encoding="utf-8") as orders:
orders.write("Another order\n")w starts a new record and replaces old text. a keeps the old text and adds the next line.
from contextlib import contextmanager
@contextmanager
def order_message(order_id):
print("Opening order", order_id)
try:
yield
finally:
print("Closing order", order_id)
with order_message("A-12"):
print("Saving order")@contextmanager is an introduction to how with can manage more than files: setup runs before yield and cleanup in finally runs afterward.
Trace one order record
- 1. Choose a modeChoose r to read, w to replace content, or a to add to the end.
- 2. Enter withPython opens the file and assigns the file object inside the block.
- 3. Read or writeUse read(), readline(), or write() for the required file operation.
- 4. Leave safelyPython closes the file automatically, even when code inside the block raises an exception.
Common mistakes
- Using w to add an orderw can erase the existing record. Use a when the earlier orders must stay.
- Forgetting encodingSpecify encoding="utf-8" for text that may contain accented or non-English characters.
- Opening without withManual close() is easy to miss when an exception interrupts the code.
- Assuming a file existsUse FileNotFoundError when reading a file that may not have been created yet.
