You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers file handling for the OCR A-Level Computer Science (H446) specification. You need to understand how programs read from and write to text files, CSV files, and binary files, as well as the difference between sequential and random access.
Data stored in variables is volatile -- it is lost when the program ends. Files provide persistent storage, allowing data to be saved and retrieved between program executions.
| Storage Type | Volatile? | Example |
|---|---|---|
| Variables (RAM) | Yes | Program variables, arrays |
| Files (disk) | No | Text files, databases, images |
When opening a file, you specify a mode that determines how the file can be accessed:
| Mode | Description | Creates File? | Overwrites? |
|---|---|---|---|
"r" | Read -- open for reading only | No (error if not found) | No |
"w" | Write -- open for writing; creates file or overwrites existing | Yes | Yes |
"a" | Append -- open for writing; adds to end of file | Yes | No |
"r+" | Read and write | No | No (but can overwrite at position) |
"rb" | Read binary | No | No |
"wb" | Write binary | Yes | Yes |
# Using 'with' ensures the file is automatically closed
with open("students.txt", "r") as file:
content = file.read()
print(content)
with open("students.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes trailing newline
with open("students.txt", "r") as file:
lines = file.readlines()
# lines is a list of strings, one per line
for line in lines:
print(line.strip())
file = OPENREAD("students.txt")
WHILE NOT file.endOfFile()
line = file.readLine()
OUTPUT line
ENDWHILE
file.close()
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is line 2\n")
with open("log.txt", "a") as file:
file.write("New log entry\n")
file = OPENWRITE("output.txt")
file.writeLine("Hello, World!")
file.writeLine("This is line 2")
file.close()
Exam Tip: Always remember to close files after use. In Python, the
withstatement does this automatically. In pseudocode, always showfile.close(). Failure to close a file can result in data loss or corruption.
CSV (Comma-Separated Values) files store tabular data as plain text, with each value separated by a comma and each row on a new line.
Name,Age,Grade
Alice,17,A
Bob,18,B
Charlie,17,C
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
header = next(reader) # Skip header row
for row in reader:
name = row[0]
age = int(row[1])
grade = row[2]
print(f"{name} (age {age}): Grade {grade}")
import csv
students = [
["Alice", 17, "A"],
["Bob", 18, "B"],
["Charlie", 17, "C"]
]
with open("students.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "Grade"]) # Header
writer.writerows(students) # All data rows
import csv
# Reading with DictReader
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['Name']}: {row['Grade']}")
# Writing with DictWriter
with open("output.csv", "w", newline="") as file:
fieldnames = ["Name", "Age", "Grade"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"Name": "Diana", "Age": 18, "Grade": "A*"})
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.