Open, read, write, and append files using open() and the with statement
Parse CSV data using the csv module
Read and write JSON files with the json module
Understand file modes: r, w, a, x
📄 File Operation Simulator
Simulate reading and writing text files, parsing CSV lines, and working with JSON — all in the browser without needing a real filesystem.
Output:
Opening Files
Python's built-in open() function opens a file and returns a file object. Always use the with statement — it automatically closes the file even if an exception occurs.
with open("data.txt", "r") as f: — Opens for reading. The file is closed automatically when the with block exits.
File Modes
"r" — Read (default). Raises FileNotFoundError if file doesn't exist.
"w" — Write. Creates file if missing; truncates (erases) if it exists.
"a" — Append. Creates if missing; adds to the end if it exists.
"x" — Exclusive create. Raises FileExistsError if file already exists.
Add "b" for binary mode (images, PDFs): "rb", "wb".
CSV and JSON
Most real data lives in CSV or JSON format. Python's standard library includes modules for both:
import csv — csv.reader(f) iterates rows as lists. csv.DictReader(f) gives each row as a dict keyed by column headers.
import json — json.load(f) parses a JSON file into a Python dict/list. json.dump(data, f) writes Python data as JSON. json.dumps(data) returns a JSON string.
Quick Check
1. Why use with open(...) as f: instead of just f = open(...)?
with is faster at reading large files
with automatically closes the file when the block exits, even if an error occurs
open() doesn't work without with in Python 3
with provides a progress bar for large files
2. Which mode should you use to add lines to the end of an existing log file without erasing it?
"r"
"w"
"a"
"x"
3. What does json.loads('{"name":"Alice"}') return?
A string
A JSON object
A Python dictionary: {'name': 'Alice'}
A list with one element
4. What is the difference between csv.reader and csv.DictReader?
DictReader is slower but more accurate
reader gives each row as a list; DictReader gives each row as a dict with column names as keys
DictReader only works if the CSV has exactly two columns