Revise Computing
Revision notesQuestionsFor schools
Log inStart revising free
Revision notesQuestionsFor schoolsLog in
GCSE Computer Science/Supplementary programming practice/File Handling Techniques

Closing files

301.15 File Handling Techniques

Practise exam questions

File Handling Techniques — Note 4 of 4

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.

What to know

  • 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
← Previous noteWriting files301.15 File Handling TechniquesNext topic →Anticipate misuse301.16 Defensive Design

Back to File Handling Techniques

Specification notes for programming are in Paper 2.

File Handling Techniques

Note 4 of 4

  1. 1Opening files
  2. 2Reading files
  3. 3Writing files
  4. 4Closing files
Topic overview

© 2026 Revise Computing · revisecomputing.co.uk

Privacy noticeTermsContact

Revise Computing is an independent revision resource. It is not affiliated with, or endorsed by, OCR (Oxford Cambridge and RSA Examinations).