Python file handling
Open, read, write and append text files safely using the specified Python operations and modes.
Section 10 · Further programming and testing
Mapped to the Cambridge IGCSE Computer Science 0265 syllabus for exams in 2029. These original explanations and self-checks are independent study support, not Cambridge papers, official marks or grades. Practical programming is taught with worked code and trace tasks; an executable Python workspace and timed digital-exam simulation are not yet available.
Before you begin
- Use the 2029 syllabus for this course. Cambridge specifies Python 3.10 or higher for programming and digital exams for both components. The syllabus currently identifies this route for 2029 only; confirm later-year availability with Cambridge and your school.
Work on paper. Try each question before revealing help, and explain why your method works.
Quick readiness check
Before python file handling, which statement is the safest starting point?
What you will learn
- Explain why programs use files for persistent data
- Use open(), close() and with open()
- Select read, write or append mode and file-reading methods
Files keep data between program runs
Variables are normally lost when a program ends. A file stores information on backing storage so a later run can retrieve or update it. Choose a data format and location that match the program's requirements.
open() creates a file object. Mode 'r' reads, 'w' writes and replaces existing content, and 'a' appends to the end. close() releases the file after use. with open(...) automatically closes the file when the block finishes, even when an error occurs.
Read and write deliberately
read() returns the file contents, readline() reads one line and readlines() returns the lines as a list. write() sends text to a file; add a newline explicitly when separate records need separate lines.
Writing with 'w' can erase previous content, so use it only when replacing is intended. Use 'a' to preserve existing content and add more. Handle missing files and invalid data as run-time conditions in a real program.
Pause and explain
Which habit best checks your understanding of python file handling?
Worked example
Append the line 'Mina,82' to scores.txt and make sure the file closes.
Show the worked solution
- Open the file in append mode so existing records remain.
- Write the text and a newline.
- Use a with block to close it automatically.
Answer with open("scores.txt", "a") as file: file.write("Mina,82\n")
Try a topic test
Choose Easy, Normal or Difficult. Save your answers and open worked review after finishing.
Test this topic →From guided practice to a new situation
Write your answer and reasoning first. Use a hint only if you are stuck. The model solution is for self-checking; your written work is not automatically marked.
Write Python to read all lines from notes.txt using with open().
Give me a hint
Use readlines() inside a context manager.
Compare my reasoning
- Start a with open call in 'r' mode.
- Bind the file object to a name.
- Call readlines() and store or process the returned list.
with open("notes.txt", "r") as file: lines = file.readlines()
Look for these in your work
- Read mode
- Context manager
- Lines stored
Explain why opening a log in 'w' mode is risky when previous entries must be retained, and choose the right mode.
Give me a hint
Compare replacement with appending.
Compare my reasoning
- 'w' replaces existing file contents when opened.
- That can delete the previous log.
- Use 'a' to add new entries to the end.
Use append mode 'a'; 'w' would replace the old log.
Look for these in your work
- Write behaviour
- Risk stated
- Mode chosen
A program saves two records, one after the other, but they appear on one line. Explain the cause and correction.
Give me a hint
Consider how write() handles line breaks.
Compare my reasoning
- write() does not automatically add a newline.
- The first record must include '\n' before the next record is written.
- Alternatively, write each record through a method that deliberately adds a line ending.
Add a newline character between records because write() does not insert one automatically.
Look for these in your work
- Cause
- Correction
- File format impact
Common mistakes
- Opening in 'w' when old data must be kept.
- Forgetting newlines between records.
- Leaving a file open after the operation.
What can you explain now?
Which mode adds data to the end without replacing existing content?
Compare with the explanation
'a'
Append mode retains previous content and writes at the end.
After trying it yourself, choose your next review. This is your self-assessment.
Your review choice appears on Today. Sign in to sync it across devices.
Make it stick
How do file modes, reading methods and context managers affect persistent data?
If you needed the solution, close it and solve the problem again from a blank page. A correct answer is stronger when you can explain the reason for each step.