File Handling
A text file is a file in secondary storage that stores lines of characters. The file handling you need uses text files, so each line is text: when a program reads a line, it receives a string, even if the characters look like a number.
A mode states how a file will be used when it is opened. In Python you give the mode as a short string to open(), such as "r" for read mode or "w" for write mode. The mode controls what happens to the file's contents.
| Mode | Mode string | File must already exist? | Effect on the file |
|---|---|---|---|
| Read | "r" | Yes | Keeps the contents and reads from the first line |
| Write | "w" | No | Wipes existing contents; creates a new file if needed |
| Append (extra) | "a" | No | Keeps existing contents and adds new data at the end |
Read mode opens a file that already exists so you can read it from the start. If the file is missing, Python causes an error rather than making a blank file.
Write mode creates a new file when the name is not there. If the file does exist, opening it in write mode wipes its old contents, ready for a fresh set of data.
An extra mode called append mode is not required by the specification, so questions will not depend on it. It adds new data to the end of a file instead of wiping it, so the existing contents are kept.
OCR GCSE Computer Science · File Handling