File Input and Output
Outcome 7: File Input and Output · Blueprint Pillar 3 · PGCC INT-1700 (interim) · Download .docx
Objectives
- Open a file using open() with the correct mode and close it properly.
- Use the with statement to manage file context automatically.
- Read file contents using read(), readline(), and readlines().
- Write to a file using write() and distinguish write mode from append mode.
- Read and write CSV files using Python's csv module.
Key terms
- open()
- Built-in function that opens a file and returns a file object: open(path, mode).
- file mode 'r'
- Read mode — opens an existing file for reading; raises FileNotFoundError if it does not exist.
- file mode 'w'
- Write mode — creates a new file or overwrites an existing one entirely.
- file mode 'a'
- Append mode — opens or creates a file and adds new content at the end without erasing existing data.
- with statement
- A context manager that automatically calls close() when the indented block exits, even if an exception occurs.
- read()
- Reads the entire file as a single string.
- readline()
- Reads and returns one line at a time from the file.
- readlines()
- Reads all lines and returns them as a list of strings including newline characters.
- write()
- Writes a string to the file at the current position; does not add a newline automatically.
- CSV
- Comma-Separated Values — a plain-text format storing tabular data with one record per line.
The concept
Files allow programs to store data between runs and exchange data with other programs. Without files, every program starts fresh — nothing is saved. Files are the bridge between a program's in-memory computation and persistent storage.
Opening a file requires open(). It takes two arguments: the file path and the mode. Modes: 'r' opens for reading (file must exist); 'w' opens for writing and wipes any existing content; 'a' opens for appending, preserving existing content and adding new data at the end; 'r+' opens for both reading and writing. The return value is a file object with methods for reading and writing.
The with statement is the recommended way to open files. with open('data.txt', 'r') as f: automatically closes the file when the block ends — even if an exception occurs. This prevents resource leaks. Without with, you must call f.close() explicitly, and forgetting this is a common error that can corrupt files or leave them locked.
Reading has three patterns. f.read() returns all content as one big string — efficient for small files. f.readline() returns one line (including the newline character at the end) — useful for processing a file line by line in a loop. f.readlines() returns a list where each element is one line — convenient when you need random access to lines.
Writing uses f.write(string). Note that write() does not automatically add a newline — you must include '\n' where lines should break. In 'w' mode, opening the file creates it new or erases existing content. In 'a' mode, new data is added after existing content.
CSV (Comma-Separated Values) is the most common format for tabular data. Python's csv module (import csv) provides csv.reader(f) to iterate rows as lists, and csv.writer(f) with writer.writerow([...]) to write rows. Using the csv module handles edge cases like quoted fields with commas inside them.
Blueprint Pillar 3 — Technology and Society: File I/O is fundamental to nearly every real application. Student records, medical data, financial transactions, application logs, and machine learning datasets all live in files. Understanding how to open, read, write, and close files correctly — and how to handle errors when files are missing or malformed — is essential to building reliable software.
Worked examples
Common mistakes
- Using 'w' mode when you mean 'a'. Opening in write mode ('w') deletes all existing content. Use 'a' when you want to add to an existing file.
- Forgetting to strip newlines when reading. f.readlines() includes '\n' at the end of each string. Use line.strip() or line.rstrip('\n') before processing.
- Trying to read a file that does not exist. 'r' mode raises FileNotFoundError if the file is missing. Wrap in try/except FileNotFoundError to handle this gracefully.
Self-check
Try each one before you look. A miss here costs nothing and tells you exactly what to reread.
Canvas is the official record. This companion enhances the PGCC curriculum; it does not replace it. Last name and class year only. Students with a 504 plan or IEP: your accommodations apply.