Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTafadzwa Timothy Gakaka
10,978 PointsOnce a file is open, how do you remove it from memory? file_object.()
Once a file is open, how do you remove it from memory?
file_object.()
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsThe short answer is to use the method file_object.close()
.
An idiom of Python is to use the with
statement:
with open(filename, "r") as f:
# some code that operates on f
pass
# when this code block exists, the `with` statement will automatically close the file `f`
# file is now closed. The variable `f` will still point at an object, but it can not be operated upon
>>> f
<_io.TextIOWrapper name='file_f' mode='r' encoding='UTF-8'>
>>> f.readlines()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
>>> f.closed
True
>>> f.__sizeof__()
192
If you need to delete the object entirely use del f
.
Post back if you need more help. Good luck!!