File Handling
Moving data from volatile RAM into non-volatile Hard Drive storage.
The Whiteboard vs The Notebook
When a Python programme is running, all variables and lists are stored in RAM. RAM is like a classroom Whiteboard: it's fast and flexible, but when the bell rings (the programme ends), the teacher wipes the board completely clean.
To stop our data from being deleted, we must physically copy it from the Whiteboard into a permanent Notebook (A text file on the Hard Drive). This process is known as File Handling.
The 4 Core Operations
1. Open
Open the notebook page.
f = open("log.txt")
2. Read
Pulling data into variables.
x = f.readline()
3. Write
Pushing variables to the file.
f.write("Hello")
4. Close
Saving and avoiding data leaks.
f.close()
Examiner's Eye - Forgetting to Close!
A very common trap in writing code is forgetting the .close() command. If you write an algorithm but fail to close the file at the end, your data might not physically commit to the hard drive, resulting in a lost mark.
The File Modes
Whenever you open a file, you must declare your intent. Click to reveal what each letter means.
Allows viewing data. Attempting to write in "r" mode will cause an error.
Instantly WIPES the file clean. Starts writing from a totally blank page.
Safely opens the file and places your cursor exactly at the BOTTOM, keeping old data safe.
Reading Files & String Slicing
When you successfully read a line from a text file, it enters your RAM as a raw String. You will often need to use String Slicing to extract the specific characters you actually care about.
# 1. Open the file carefully in Read mode
myFile = open("codes.txt", "r")
# 2. Extract the first line. Imagine it says "ERR_Connection_Lost"
lineData = myFile.readline()
# 3. String Slicing: Only grab the very first 3 characters [0:3]
errorPrefix = lineData[0:3]
# 4. Prove it worked and seal the file.
print(errorPrefix) # Output: ERR
myFile.close()
CSV Array Parsing
Grade 9 StretchReal-world databases save data as CSV (Comma-Separated Values). Because reading from a file treats everything as one giant string, high-tier programmers use the .split() string manipulation technique to fracture that string into an Array automatically.
-
heroArray[0]securely holds "Tony". -
heroArray[1]securely holds "Stark". -
heroArray[2]securely holds "45".
Check Your Understanding
1. I execute open("savegame.txt", "w") on a file that already has 5 hours of saved player data in it. What happens?
2. You read a string from a file that perfectly holds: "BANNED_USER". What does the string slice [0:6] evaluate to?
Written Exam Scenario (AO2)
Core GCSE Practice"A program reads a security log file line by line. One line of text is read into the variable eventLog and reads exactly: Warning,CPU_Hot.
Write an algorithm that opens the file log.txt in an appropriate reading mode, reads the first line into a variable, splits the comma-separated data into an array called dataArray, and securely closes the file." (4 marks)
myLog = open("log.txt", "r")
eventLog = myLog.readline()
# Advanced split logic
dataArray = eventLog.split(",")
# Safety closure
myLog.close()
M1: Opening the file in Read ("r") mode.
M2: Reading a line from the file object into a variable.
M3: Executing a `.split(",")` specifically targeting commas.
M4: The presence of the `.close()` method.