StayTalentReady

File Input and Output

Outcome 7: File Input and Output · Blueprint Pillar 3 · PGCC INT-1700 (interim) · Download .docx

Objectives

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

Example 1: Write a list to a file and read it back: names = ['Jordan', 'Sam', 'Alex']. with open('names.txt', 'w') as f: for name in names: f.write(name + '\n'). Then read: with open('names.txt', 'r') as f: lines = f.readlines(). result = [line.strip() for line in lines]. print(result). Output: ['Jordan', 'Sam', 'Alex']. strip() removes the '\n' from each line.
Example 2: Appending to a log file: def log_event(message): with open('log.txt', 'a') as f: f.write(f'{message}\n'). Each call to log_event() adds a line without erasing previous entries. Mode 'a' is essential here — using 'w' would erase all prior log entries on every call.

Common mistakes

Self-check

Try each one before you look. A miss here costs nothing and tells you exactly what to reread.

1. Which file mode opens an existing file for reading without creating or changing it?
2. What is the primary advantage of using `with open(...) as f:` instead of `f = open(...)`?
3. You want to add new lines to an existing file WITHOUT erasing its current content. Which mode is correct?
4. Which method reads an ENTIRE file's content as a single string?
5. After writing: f.write('Hello'). What character must you add to place the NEXT write on a new line?

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.

← Lists and Data StructuresTesting and Debugging →

↑ Back to top