Knowledge organisersFile Handling Techniques
Close file when done.
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.
with open() as f: closes automatically at end of blockwith, you must call f.close() manually# 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