Data Structures and Object-Oriented Programming

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 writeWhat it meansTypical use
open("example.txt", "r")read-onlyWhen you only want to look
open("example.txt", "w")write (erase & start fresh)When you’re replacing everything
open("example.txt", "a")appendWhen 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

MethodResultGood for
read()The whole file as one big stringSmall files
readline()One line each time you call itStepping through line by line
readlines()A list where each item is a lineQuick “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

FunctionDirectionMemory vs. Disk
json.dumps(py_obj)Python ➜ stringMemory
json.loads(json_str)string ➜ PythonMemory
json.dump(py_obj, file)Python ➜ fileDisk
json.load(file)file ➜ PythonDisk

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:

  1. Try something risky.
  2. If Python raises a matching except block, run that block.
  3. Program keeps going instead of crashing.

7. Cleaning text with strip() & rstrip()

MethodRemovesFrom where
strip()blanks or given charsboth ends
rstrip()blanks or given charsright 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

  1. Files need a mode: "r", "w", or "a".
  2. Read with read(), readline(), or readlines().
  3. Always close files—or simpler—use with.
  4. JSON is the go-to for saving dictionaries/lists.
  5. Handle mistakes gracefully with try / except.
  6. strip() and friends tidy up messy strings.

9. Practice prompts

  1. Write a program that appends today’s date to journal.txt each time it runs.
  2. Convert a list of Python dictionaries (contacts) into contacts.json, then read it back and print each name.
  3. Ask the user for a filename, open it safely, and count how many non-empty lines it contains, handling “file not found” errors politely.
Back to Data Structures and Object-Oriented Programming