Edexcel 1CP2 · GCSE Computer Science · ~11 min read · 🔒 Pro
Notes
──
Video
──
Slides
──
Worksheet
──
Quiz
Why File Handling?
Variables are stored in RAM — they are lost when a program ends. Files allow data to be persisted (saved permanently) to secondary storage. File handling is essential for programs that need to save results, load settings, or process data across multiple runs.
Opening and Closing Files
Use the built-in open() function. Always close files when done (or use with which closes automatically).
Mode
Meaning
Creates file?
Overwrites?
"r"
Read (default)
No — file must exist
No
"w"
Write
Yes
Yes — wipes content
"a"
Append
Yes
No — adds to end
"r+"
Read and write
No — file must exist
No
Reading from Files
# Method 1: read() — reads the WHOLE file as one stringwithopen("data.txt", "r") as f: content = f.read()print(content)# Method 2: readline() — reads ONE line at a timewithopen("data.txt", "r") as f: line = f.readline()print(line)# Method 3: readlines() — reads ALL lines into a LISTwithopen("data.txt", "r") as f: lines = f.readlines() # ['line1\n', 'line2\n', ...]for line in lines:print(line.strip()) # .strip() removes \n# Method 4: iterate directly (most Pythonic)withopen("data.txt", "r") as f:for line in f:print(line.strip())
Writing to Files
# Write mode — OVERWRITES existing contentwithopen("output.txt", "w") as f: f.write("Hello, World!\n") # \n adds newline f.write("Second line\n")# Append mode — ADDS to existing contentwithopen("output.txt", "a") as f: f.write("Third line added later\n")
The with Statement
Using with open() as f: is recommended because it automatically closes the file when the block ends — even if an error occurs. This prevents data loss and resource leaks.
# WITHOUT with (manual close — risky)f = open("file.txt", "r")content = f.read()f.close() # must call this manually# WITH with (automatic close — recommended)withopen("file.txt", "r") as f: content = f.read()# file is automatically closed here
Exam tip: Edexcel Paper 2 may ask you to write programs that read from or write to text files. Know all three read methods (read, readline, readlines), know that "w" overwrites but "a" appends, and always use the with statement for file handling.
⚠️ Common Mistakes
Using "w" mode when you want to add to a file — "w" wipes ALL existing content!
Forgetting to add "\n" at the end of each line when writing
Not stripping "\n" from lines when reading — each line includes a newline character
Trying to open a file in "r" mode when it doesn't exist — causes FileNotFoundError
Forgetting to close the file when not using 'with' — causes data to not be saved
✅ Notes completed!
▶
Video coming soon
Click slide or press arrow keys to navigate
✍️
Worksheet — 6.3c File Handling
8 Edexcel-style questions · instantly marked
Q1State the difference between opening a file in "w" mode and "a" mode.[2]
✅ Mark scheme
"w" (write) mode overwrites all existing content in the file (or creates it if it doesn't exist) [1]; "a" (append) mode adds new content to the END of the file without removing existing data [1].
Q2Write Python code to write the text "Hello, World!" followed by "Goodbye!" on separate lines to a file called "greetings.txt".[3]
✅ Mark scheme
with open("greetings.txt", "w") as f: [1]; f.write("Hello, World!\n") [1]; f.write("Goodbye!\n") [1]. Must include "\n" for separate lines. Accept print() to file using file=f parameter.
Q3Write Python code to read ALL lines from a file called "names.txt" into a list, then print each name without the newline character.[4]
✅ Mark scheme
with open("names.txt", "r") as f: [1]; lines = f.readlines() [1]; for line in lines: [1]; print(line.strip()) [1]. .strip() removes the newline character (\n) from each line. Accept .rstrip() or .rstrip('\n') instead of .strip().
Q4Why is it recommended to use the 'with' statement when opening files?[2]
✅ Mark scheme
The 'with' statement automatically closes the file when the block ends [1]; this happens even if an error occurs during processing, preventing data loss and resource leaks — no need to call f.close() manually [1].
Q5What is the difference between .read(), .readline(), and .readlines()?[3]
✅ Mark scheme
.read() reads the ENTIRE file content as a single string [1]; .readline() reads ONE line at a time (calling it again gets the next line) [1]; .readlines() reads ALL lines and returns them as a list (each item is a line including \n) [1].
Q6A student opens a file in "r" mode but the file doesn't exist. What happens, and how could this be prevented?[2]
✅ Mark scheme
A FileNotFoundError is raised and the program crashes [1]; prevention: use try/except to handle the error gracefully, or check if the file exists first using os.path.exists() before opening [1].
Q7Write Python code that reads scores from "scores.txt" (one number per line) and calculates the average score.[5]
✅ Mark scheme
with open("scores.txt", "r") as f: [1]; lines = f.readlines() [1]; total = 0; count = 0 [1]; for line in lines: total += int(line.strip()) [1]; count += 1; print(total / count) [1]. Must convert to int/float since file returns strings.
Q8Explain why data stored in a variable is lost when a program ends, but data written to a file is not.[2]
✅ Mark scheme
Variables are stored in RAM (primary storage) which is volatile — it loses its contents when the power is removed or the program ends [1]; files are stored on secondary storage (hard drive / SSD) which is non-volatile — data persists even without power [1].
Topic Quiz
Q 1 of 15
You scored
out of 15
Click to reveal definition
🎉
Session complete!
Term
Definition
🎯
Mini Test — File Handling
Timed exam-style test — 10 minutes.
⏱10:00
Section A — Multiple Choice [5 marks]
Q1Which file mode opens a file for reading only?[1]
Q2Which method reads ALL lines from a file into a list?[1]
Q3A file has content "Hello\nWorld". Opening it in "w" mode and writing "Test" results in:[1]
Q4What character must you include to start a new line when writing to a file?[1]
Q5Why is secondary storage used for files instead of RAM?[1]
Section B — Short Answer
Q6Write Python code to open "log.txt" in append mode and write the line "User logged in at 10:00". The file should not be overwritten.[3]
Mark schemewith open("log.txt", "a") as f: [2 — 1 for "a" mode, 1 for with statement]; f.write("User logged in at 10:00\n") [1]. Must use "a" not "w" to avoid overwriting.
Q7What is the purpose of calling .strip() on each line when reading from a text file?[2]
Mark schemeEach line read from a file includes a newline character (\n) at the end [1]; .strip() removes this whitespace (and any leading/trailing spaces), giving just the actual data on the line [1].