🔒

Unlock Pro

Subscribe to access all 59 Edexcel 1CP2 lessons.

£7.99/month
or £59/year
🐍 Paper 2 · Topic 6: Programming
6.3c File Handling in Python
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).

ModeMeaningCreates file?Overwrites?
"r"Read (default)No — file must existNo
"w"WriteYesYes — wipes content
"a"AppendYesNo — adds to end
"r+"Read and writeNo — file must existNo

Reading from Files

# Method 1: read() — reads the WHOLE file as one string with open("data.txt", "r") as f: content = f.read() print(content) # Method 2: readline() — reads ONE line at a time with open("data.txt", "r") as f: line = f.readline() print(line) # Method 3: readlines() — reads ALL lines into a LIST with open("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) with open("data.txt", "r") as f: for line in f: print(line.strip())

Writing to Files

# Write mode — OVERWRITES existing content with open("output.txt", "w") as f: f.write("Hello, World!\n") # \n adds newline f.write("Second line\n") # Append mode — ADDS to existing content with open("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) with open("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
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!
TermDefinition
🎯

Mini Test — File Handling

Timed exam-style test — 10 minutes.

← 6.3b Tuples & DictsTopic 6 · PythonNext: 6.4a Defensive Design →