`open()` starts working with a file. Give it a filename, and it returns a file handle: a special object that connects the program to that file. A filename such as `"drinks.txt"` is only a string; the handle is what lets the program read or write the file. section 5.0
Open a menu file
Start with one small line: `f = open("drinks.txt")` Here, `f` stores the file handle. With no mode supplied, the file opens for reading. The handle can then use methods such as `read()` or `readlines()` to bring the menu contents into the program. section 5.0
f = open("drinks.txt")
drinks = f.read()
print(drinks)
This tiny program opens `drinks.txt`, reads its contents through `f`, and prints the resulting text. section 5.0
Reading can produce different kinds of values. `f.read()` returns the whole file as one string. `f.readlines()` returns a list whose items include newline characters, so `strip()` can clean each item before it is used in a menu. section 5.0
Reuse file-opening code
A function can accept a filename, open that file, read its lines, strip them, and return a clean list. Calling the same function with `"drinks.txt"`, `"flavors.txt"`, and `"toppings.txt"` lets one menu program load several sets of choices. section 5.0
To save rather than read, pass a mode as the second argument. `open("orders.json", "w")` uses write mode. In write mode, Python creates the named file if it does not already exist. After saving structured data with `json.dump()`, close the handle with `f.close()`. section 8.0
import json
order = {
"name": "Erik",
"drink": "coffee",
"flavor": "caramel",
"topping": "chocolate"
}
f = open("orders.json", "w")
json.dump(order, f)
f.close()
This order-saving example opens `orders.json` in write mode, passes the handle to `json.dump()`, and then closes it. section 8.0
A friendly checklist for using `open()`:
- Choose the filename you want the program to use. section 5.0
- Store the returned file handle in a variable such as `f`. section 5.0
- Leave out the mode to read, or use `"w"` when writing a file. section 8.0
- Use the handle with file or JSON operations, then close it after writing. section 8.0
Try it yourself: make a short text file with a few choices, open it, and print what `readlines()` returns. Then clean the lines with `strip()` and use the resulting list in a menu. section 5.0








