This question is purely out of curiosity. Brought up in a recent discussion for a question here, I've often wondered why the context manager (
Close the file. A closed file cannot be read or written any more. Any operation which requires that the file be open will raise a ValueError after the file has been closed. Calling close() more than once is allowed.
with is just wrong. This behaviour has been in Python forever and thus it's worth keeping it for backward compatibility.
Because it would serve no purpose to raise an exception. If you have an actual bug in your code where you might close the file before finishing using it, you'll get an exception when using the
write operations anyway, and thus you'll never reach the second call to
Allowing this will rarely make the code easier to write avoiding adding lots of
if not the_file.isclosed(): the_file.close().
The BDFL designed the file objects in that way and we are stuck with that behaviour since there's no strong reason to change it.