[Tutor] Why do you have to close files?

Alan Gauld alan.gauld at btinternet.com
Fri Jan 27 02:16:56 CET 2012


On 26/01/12 23:20, amt wrote:

> input = open(from_file)
> indata = input.read()
>  ...
>
> output = open(to_file, 'w')
> output.write(indata)
>
> print "Alright, all done."
>
> 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()?

In this case it will work the same 99.9% of the time because when your 
program closes Python will kill all the file objects that you created 
and in the process the files will get written to the disk. However, to 
understand why you need to call close() in the general case you need to 
understand that when you do a write to a file the OS does not 
immediately write the data to the disk (it would be too slow). Instead 
it writes it to a holding area in memory (called a buffer) and then, 
every so often, it copies the buffer out to the real file. When you call 
close() one of the things that happens is that the buffer gets told to 
write to disk, even if it's not full yet. If you don't call close you 
can wind up with data missing from the end of your files.

The other thing that close does is releases the memory and other OS 
resources that are allocated to the file when you open it. Depending on 
the OS there may be limits to how many files can be open at once. Also 
the file may be locked until it is closed preventing other programs from 
accessing it. So in general, whenever you finish using a file, you 
should close it as a good habit... In fact it's a good idea to use a 
try/finally construct to guarantee that the file gets closed, especially 
if you are writing to it:

try:
    foo = open(myFiule,'w')
    # do stuff to foo
finally:
    foo.close()

The only exception to this is if you open the file like this:

with open(myfile) as aFile:
      # use aFile

This construct specifically guarantees to close the file for you at the 
end of the block.

It's one of those things that catches beginners out regularly because 
nine times out of ten not closing the file will seem to work fine then, 
once in a while, it fails and data gets corrupted.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list