SLIDE 1
CSZone.co.uk
Click to advance · Arrow keys also work
Edexcel 1CP2 · Topic 6 · 6.3c

File Handling
in Python

open() · r / w / a modes · read() · write() · with statement

CSZoneEdexcel GCSE Computer Science 1CP2
Opening & Reading Files

Reading Text Files

# Read entire file
file = open("data.txt", "r") # "r" = read mode
contents = file.read()
print(contents)
file.close() # always close!

# Better — using 'with' (auto-closes)
with open("data.txt", "r") as file:
for line in file:
print(line.strip())
"r": read mode — file must already exist; FileNotFoundError if it doesn't
The with statement automatically closes the file even if an error occurs
.strip(): removes the trailing newline \n from each line when reading
Writing & Appending Files

Saving Data to Files

# Write mode — overwrites existing content!
with open("output.txt", "w") as file:
file.write("Hello World\n")
file.write("Line 2\n")

# Append mode — adds to end of file
with open("output.txt", "a") as file:
file.write("This is appended\n")
"w": write — creates file if it doesn't exist; overwrites if it does
"a": append — adds to the end of the file without deleting existing content
Always use \n to add a newline at the end of each written line
Practical File Example

Storing Student Records

names = ["Alice", "Bob", "Charlie"]

# Write all names to file
with open("students.txt", "w") as f:
for name in names:
f.write(name + "\n")

# Read back and print
with open("students.txt", "r") as f:
data = f.readlines() # list of lines
for line in data:
print(line.strip())
readlines(): reads all lines into a list; readline(): reads one line at a time
Exam Practice

Have a go at this question

Edexcel-style question
Explain the difference between opening a file in "w" mode and "a" mode in Python.
2 marks
"w" (write) mode overwrites all existing content in the file [1]. "a" (append) mode adds new content to the end of the file without deleting what was already there [1].
Key Takeaways

What to Remember

"r" = read; "w" = write (overwrites); "a" = append (adds to end)
Always close files — use with open(...) as f: to auto-close safely
Read: .read() (all), .readlines() (list), .readline() (one line)
Use .strip() to remove newline characters when reading lines