8.1 Programming

Show All Section Notes

File Handling

WHY USE FILES?

In your Python programs, variables are stored in RAM (Temporary). When you close the program, the data is gone. Files allow us to store data in Secondary Storage (Permanent) so we can load it again later.

1. The 3 Steps of File Handling

  1. Open the file: Tell the computer which file you want and if you want to Read (r) or Write (w).
  2. Process: Read data from the file or write data into it.
  3. Close the file: Very important! This saves your changes and frees up memory.

2. Python Examples for IGCSE

A. Writing to a File

# This creates a file called 'names.txt' file = open("names.txt", "w") file.write("Alice\n") file.write("Bob\n") file.close() # Always close your file!

B. Reading from a File

# Opens the file in 'read' mode file = open("names.txt", "r") for line in file: print(line.strip()) # .strip() removes the extra newline file.close()
📝 IGCSE Exam Tip:

You might be asked: "What happens if you open a file for writing ('w') that already has data in it?"
Answer: The old data is deleted (overwritten). To keep old data, use append ('a').

Ready for the next IGCSE topic: Logic Gates or Input/Output Devices?