Open, read, write and close files
📁 File Handling in Python (Cambridge IGCSE 0478)
Opening Files
Think of a file as a diary 📓. To read or write, you first open it, just like opening a diary to start writing.
file = open('data.txt', 'r') # 'r' = read mode
file = open('data.txt', 'w') # 'w' = write mode (overwrites)
file = open('data.txt', 'a') # 'a' = append mode (adds to end)
- Use
'r'for reading only. - Use
'w'to create a new file or overwrite. - Use
'a'to add new content without deleting existing data.
Reading Files
Once the diary is open, you can read its contents. Python offers several ways:
- Read the whole file:
content = file.read() - Read line by line:
for line in file: print(line.strip()) - Read all lines into a list:
lines = file.readlines()
Remember: Always close the file after reading.
Writing Files
Writing is like adding new entries to your diary. Use the following pattern:
with open('data.txt', 'w') as file:
file.write('Hello, world!\')
file.write('Second line.')
Using with automatically closes the file, but if you open it manually, you must close it yourself.
Closing Files
Just as you close a diary after writing, you must close a file to free resources:
file.close()
Or use with for automatic closing:
with open('data.txt', 'r') as file:
data = file.read()
Common Errors & How to Avoid Them
- FileNotFoundError: Trying to read a file that doesn't exist. Use
try/exceptor check withos.path.exists(). - PermissionError: Trying to write to a read‑only location. Ensure you have write permissions.
- Unclosed File: Leaving a file open can lock it. Use
withor remember to callclose().
Exam Tips
When answering exam questions about file handling, keep these points in mind:
- Show the correct mode for the task (e.g.,
'r'for reading,'w'for writing). - Include the file path (relative or absolute) and explain why it matters.
- Demonstrate reading or writing with code snippets.
- Explain the importance of closing the file or using
with. - Use an analogy (like a diary) to show understanding.
Good luck! 🚀
Revision
Log in to practice.
0 views
0 suggestions