Understand why data is stored in external files and how programs can access them
File Handling in IGCSE Computer Science
Objective: Understand why data is stored in external files and how programs can access them.
Why Store Data in Files?
Think of your computer as a library. 📚 Files are like books that keep information safe even after you close the library (turn off the computer).
- Data persistence: keeps information between program runs.
- Sharing: multiple programs can read/write the same file.
- Backup: files can be copied to another location.
How Programs Access Files
Programs use file I/O operations. In many languages you open a file, read/write, then close it.
- Open:
open('data.txt', 'r') - Read/Write:
read(),write() - Close:
close()
Example in Python:
with open('scores.txt', 'r') as file:
data = file.read()
Common File Operations
| Operation | Description | Example (Python) |
|---|---|---|
| Read | Retrieve data from file. | file.read() |
| Write | Add data to file. | file.write('Hello') |
| Append | Add data to end of file. | file.write('New line', mode='a') |
| Delete | Remove file from storage. | os.remove('file.txt') |
File Paths and Directories
Understand the difference between absolute and relative paths.
- Absolute:
/home/user/documents/file.txt - Relative:
../data/file.txt
Exam Tips
Tip 1: Remember the open() function syntax and modes: 'r', 'w', 'a'.
Tip 2: Use the with statement to automatically close files.
Tip 3: When asked to write a program, outline steps: open, read/write, close.
Practice Question
Write a short program that reads a file called students.txt and prints each name on a new line. Use a for loop.
Analogy Recap
Just like a diary keeps your thoughts safe, files keep data safe for your programs. 📝
Revision
Log in to practice.