[Tutor] Why do you have to close files?

Andre' Walker-Loud walksloud at gmail.com
Fri Jan 27 00:48:25 CET 2012


>> Exercise 17, extra credit 6 Learn python the hard way: Find out why
>> you had to do output.close() in the code.
>> 
>> 
>> Code:
>> 
>> output.close()
>> input.close()
>> 
>> 
>> I don't get it. If you don't close input and output it works exactly
>> the same as if you would close them, so why do you have to do
>> output.close() and input.close()?
>> 
>> Also does it matter if you do: input.close() and then output.close()?
>> Is there an order to follow?
>> 
> There's no order to follow, and it's really more about cleaning up after yourself than being a necessity. If you were writing to real files, your operating system would limit how many open files you could have at any time, so you want to make sure you close file handles you're no longer using.

Also - from experience, output.close() can be very important.

eg. - I often use python to
1- create an initialization file
2 - use this initialization file with some executable code

These are steps I perform in the same script.  One time, I forgot to do "output.close()" before handing my file to the executable.  Then for two weeks, I was wondering what was wrong with my code?!?  It compiled damn it, and if I ran my job (this is on a big computing cluster) in interactive mode, everything worked!?!  What was going wrong?????  ahhhh

Well, when I finally realized I forgot to "close()" my file, I felt rather silly.

The problem is python does not actually write the file to disk until you execute "output.close()".  When you end your session, if you forgot to do "output.close()" it will write it to disk for you (it has all the time for me at least).  But in my case, it was the same python "session" in which I was trying to both write the file, and then use it.


Andre



More information about the Tutor mailing list