✦ Python Intermediate & OOP Intermediate Python

L2 · Concept 05 · Advanced Python Techniques

Save the order.
Keep the record.

An online shop can keep successful orders in a file, then read that record again when it is needed.

Learning goalUse with open(...), file modes, UTF-8 encoding, and FileNotFoundError to save and read order data safely.
01 Learn02 Try03 Predict

Learning as a guest

Learning as a guest? Save your progress!

Create a free account to learn with Sloby AI, check your understanding, and track your progress.

The entire platform is free throughout 2026. Foundations stays free forever.

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 x2

Use 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.

Read safely
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.

Write versus append
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.

A small custom context manager
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. 1. Choose a modeChoose r to read, w to replace content, or a to add to the end.
  2. 2. Enter withPython opens the file and assigns the file object inside the block.
  3. 3. Read or writeUse read(), readline(), or write() for the required file operation.
  4. 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.

Python Playground

Loading Python runtime…

Change the order names, prices, or quantities. Each run creates a fresh practice file, appends one order, and then reads it.

order_log.pyPython
OutputWaiting for Python
The browser runtime is loading. You can still edit the example code.

Pyodide runs Python in a browser Web Worker. It is stopped and restarted if code keeps running. Browser execution is not a complete security boundary; do not enter secrets or rely on it for untrusted code isolation.

What text will remain in orders.txt?

Follow each mode carefully: w replaces previous text, then a adds text after it.

with open("orders.txt", "w", encoding="utf-8") as orders:
    orders.write("Keyboard x1
")

with open("orders.txt", "a", encoding="utf-8") as orders:
    orders.write("Mouse x2
")

with open("orders.txt", "r", encoding="utf-8") as orders:
    print(orders.read(), end="")
Choose the output

Practice independently

Mini Challenge — Save an order

Complete a function that adds one new order without deleting earlier orders.

Your goalUse with, mode a, and encoding="utf-8" to append the product, price, and quantity to orders.txt.

save_order_challenge.py

Optional hints
  • The mode for adding a new line while keeping old lines is "a".
  • Build the line with an f-string and end it with \n.
Ask Sloby for a hint
Sloby, the Python AI Tutor mascot

Your learning mentor

Sign in to ask Sloby

Create a free account or sign in to get AI guidance while you learn.

Sign in to check your understanding

Create a free account or sign in to receive AI feedback and save your learning progress.

Python AI Tutor · Learn by understanding, not just by running code.