when should I explicitly close a file?

Lie Ryan lie.1296 at gmail.com
Sat Apr 17 08:33:18 EDT 2010


On 04/17/10 21:23, Lawrence D'Oliveiro wrote:
> In message 
> <d48b70da-5384-4dc6-9527-46c6b735ccc0 at r1g2000yqb.googlegroups.com>, gelonida 
> wrote:
> 
>> I've been told, that following code snippet is not good.
>>
>> open("myfile","w").write(astring) ...
> 
> I do that for reads, but never for writes.
> 
> For writes, you want to give a chance for write errors to raise an exception 
> and alert the user, instead of failing silently, to avoid inadvertent data 
> loss. Hence the explicit close.

In short, in case of doubt, just be explicit.

Since in python nothing is guaranteed about implicit file close, you
must always explicitly close it.



More information about the Python-list mailing list