Closing a file with close()
Ends access to an open file so any written data is saved and the file is released. Forgetting it can lose data. A with statement closes the file for you automatically.
Understanding Closing a file with close() in QCE Digital Solutions Unit 3
What it does: The close() call comes after the write so the written data is saved to the file and the file is released. Once closed, the old file object cannot be used, so open() is called again to get a new file object. The with statement closes the file for you, even if an error occurs inside the block. An extra close() is unnecessary.
Common mistakes: close() takes no arguments and does not write anything. Line 2 should be f.write("Hi"), and close() comes after it to save the data. f.close is the method itself, so this prints a method object. To check whether the file is closed, use the attribute f.closed, which gives True or False.
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 251–337) and word search (Modules 194–337).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
file.close()Fill in the Blanks
Spot the Error
Student with a class code? Join your class →