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.

RAM (Volatile)
File (Non-Volatile)

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.

"r" Tap to flip
Read Mode

Allows viewing data. Attempting to write in "r" mode will cause an error.

"w" Tap to flip
Write Mode

Instantly WIPES the file clean. Starts writing from a totally blank page.

"a" Tap to flip
Append Mode

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 Stretch

Real-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.

# File contains: "Tony,Stark,45"
f = open("heroes.txt", "r")
record = f.readline()
# Fractures "Tony,Stark,45" into a 3-part Array!
heroArray = record.split(",")
f.close()
print("Age is: " + heroArray[2])
  • heroArray[0] securely holds "Tony".
  • heroArray[1] securely holds "Stark".
  • heroArray[2] securely holds "45".
This completely bypasses confusing string slicing by instantly generating an indexed array!

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)