CHAPTER 11 ■ FILES
172
Closing Files
Open files consume system resources, and, depending on the file mode, other programs might not
be able to access them. It’s important to close files as soon as you’re finished with them, as shown in
Listing 11-8.
Listing 11-8. Closing an Open Stream Object
>>> a_file.close()
Well that was anticlimactic.
The stream object a_file still exists. Calling its close() method doesn’t destroy the object itself, but
it’s not terribly useful anymore (see Listing 11-9).
Listing 11-9. Accessing a Closed Stream Object
>>> a_file.read() (1)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
a_file.read()
ValueError: I/O operation on closed file.
>>> a_file.seek(0) (2)
Traceback (most recent ...