Chapter 8: File Operations and JSON
1. Why files matter
Programs live in RAM, but real-world data lives on disk. Reading and writing files lets your code remember things after it stops running.
2. Opening a file safely
| What you write | What it means | Typical use |
|---|---|---|
open("example.txt", "r") | read-only | When you only want to look |
open("example.txt", "w") | write (erase & start fresh) | When you’re replacing everything |
open("example.txt", "a") | append | When you want to add to the end |
Pro tip: Use a context manager so Python closes the file for you—even if something goes wrong.
with open("example.txt", "r") as file:
content = file.read()3. Reading from a file
| Method | Result | Good for |
|---|---|---|
read() | The whole file as one big string | Small files |
readline() | One line each time you call it | Stepping through line by line |
readlines() | A list where each item is a line | Quick “grab-all” into memory |
Example:
with open("poem.txt") as f:
first_line = f.readline()
all_lines = f.readlines()4. Writing to a file
Anything you write() must be a string.
with open("log.txt", "w") as f:
f.write("Hello\n")
f.write("World\n")Need multiple lines? End each one with \n.
Writing structured data yourself
info = {"name": "Ana", "age": 25}
with open("person.txt", "w") as f:
for key, val in info.items():
f.write(f"{key}: {val}\n")Reading it back means splitting each line at ": ".
5. JSON—the universal data suitcase
JSON (JavaScript Object Notation) stores dictionaries, lists, strings, numbers, booleans, and null. Almost every language understands it.
Main functions from the json module
| Function | Direction | Memory vs. Disk |
|---|---|---|
json.dumps(py_obj) | Python ➜ string | Memory |
json.loads(json_str) | string ➜ Python | Memory |
json.dump(py_obj, file) | Python ➜ file | Disk |
json.load(file) | file ➜ Python | Disk |
Example round-trip:
import json
data = {"city": "Toronto", "temp": 18}
json_string = json.dumps(data) # to text
parsed = json.loads(json_string) # back to dict
with open("weather.json", "w") as f:
json.dump(data, f)
with open("weather.json") as f:
from_disk = json.load(f)6. Guarding against errors (Exception Handling)
try:
n = int(input("Number: "))
print(10 / n)
except ValueError:
print("Not a number.")
except ZeroDivisionError:
print("Can't divide by zero.")
except Exception as e: # catches anything else
print("Something went wrong →", e)Flow:
- Try something risky.
- If Python raises a matching except block, run that block.
- Program keeps going instead of crashing.
7. Cleaning text with strip() & rstrip()
| Method | Removes | From where |
|---|---|---|
strip() | blanks or given chars | both ends |
rstrip() | blanks or given chars | right end only |
s = " Hi! "
s.strip() # 'Hi!'
dots = "...hello..."
dots.strip(".") # 'hello'Common use: trim line endings from files:
for raw in open("names.txt"):
name = raw.strip()8. Quick recap
- Files need a mode:
"r","w", or"a". - Read with
read(),readline(), orreadlines(). - Always close files—or simpler—use
with. - JSON is the go-to for saving dictionaries/lists.
- Handle mistakes gracefully with
try / except. strip()and friends tidy up messy strings.
9. Practice prompts
- Write a program that appends today’s date to
journal.txteach time it runs. - Convert a list of Python dictionaries (contacts) into
contacts.json, then read it back and print each name. - Ask the user for a filename, open it safely, and count how many non-empty lines it contains, handling “file not found” errors politely.