[Tutor] Why do you have to close files?

Steven D'Aprano steve at pearwood.info
Fri Jan 27 00:50:03 CET 2012


amt wrote:

> 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()?

(1) It is a matter of good programming practice. If you don't close them 
yourself, Python will eventually close them for you. In some versions of 
Python, that might be the instant they are no longer being used; in others, it 
might not happen for a long time. Under some circumstances, it might not 
happen at all.

(2) When writing to a file, the data may not be written to disk until the file 
is closed. When you say "output.write(...)", the data is often cached in 
memory and doesn't hit the hard drive until the file is closed[1]. The longer 
you keep the file open, the greater the chance that you will lose data.

(3) Since your operating system has strict limits on how many file handles can 
be kept open at any one instant, it is best to get into the habit of closing 
them when they aren't needed and not wait for "maid service" to clean up after 
you.

(4) Also, some operating systems (Windows, in particular) treat open files as 
locked and private. While you have a file open, no other program can also open 
it, even just to read the data. This spoils backup programs, anti-virus 
scanners, etc.


> Also does it matter if you do: input.close() and then output.close()?
> Is there an order to follow?

It makes no real difference, but I prefer to close output files first, so they 
get written to disk a microsecond sooner than they otherwise would have.



[1] Annoyingly, modern hard drives often themselves have their own internal 
memory cache, so even when the operating system flushes data to the disk, 
there is no guarantee that the data will have actually been written to the 
disk platter. But there's nothing really you can do about that except hope 
that the power doesn't go out in the middle of writing to disk!


-- 
Steven



More information about the Tutor mailing list