open() creates a connection between a Python program and a file; read() and readline() retrieve data, write() stores data, and close() ends the connection. Together, they enable file processing, allowing data to persist after a program finishes.
How each operation works
Calling open() returns a file object, which the program uses to access the file. Its mode determines the permitted operation.
| Operation | Purpose | Important behaviour |
|---|---|---|
open(filename, mode) | Opens a file and returns a file object | Common modes are "r" for reading, "w" for writing, and "a" for appending |
read() | Reads the remaining file contents | Returns one string; read(n) reads up to n characters |
readline() | Reads one line from the current position | Usually includes the ending newline character \n |
write(data) | Writes a string to the file | Does not automatically add spaces or newline characters |
close() | Closes the file | Flushes buffered output and releases the file resource |
The file object maintains a file pointer, meaning the position at which the next read or write begins. Repeated calls to readline() therefore retrieve consecutive lines until the end of file (EOF) is reached.
file = open("scores.txt", "r")
first_line = file.readline()
remaining_text = file.read()
file.close()
To write data:
file = open("scores.txt", "w")
file.write("Alex,18\n")
file.close()
Opening with "w" creates the file if necessary but erases existing contents. Opening with "a" preserves existing data and writes at the end.
A common misconception is that write() automatically starts a new line. It does not: \n must be included explicitly.
IB exam technique
For B2.5 File processing, be ready to trace the file pointer, select an appropriate access mode, and explain why files should be closed. In pseudocode or Python questions, distinguish reading the entire remaining file with read() from processing one line at a time with readline().