Revise Computingrevisecomputing.co.uk
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates

Knowledge organisers / File Handling Techniques

Closing files

All topicsPractise exam questions
Knowledge organiser

File Handling Techniques

301.15d

Close file when done.

What you need to know

Files must be closed after use to ensure data is saved and system resources are freed. The with statement handles this automatically — it's the recommended approach.

Key points

  • Always close files when finished
  • with open() as f: closes automatically at end of block
  • Without with, you must call f.close() manually
  • Forgetting to close can lose data or lock the file

Code examples

Manual vs with
python
# Manual close (avoid)
f = open("data.txt", "r")
data = f.read()
f.close()

# Better: with auto-closes
with open("data.txt", "r") as f:
    data = f.read()
# File is already closed here