Anonymous file closing

Duncan Booth me at privacy.net
Sat Jun 12 14:53:49 CEST 2004


surferjeff at gmail.com (Jeff) wrote in
news:781dd16f.0406111108.6f2e1afd at posting.google.com: 
...
>> > text = open(filename, 'r').read()
...
>> If you aren't worried about portability, and you are using the C 
>> implementation of Python then you may find it is closed immediately
>> but it is poor practice to depend on it.
> 
> This is true, but I recommend:
> 
> 1. Only use the C implementation of Python, a.k.a. The Implementation.
> 2. Depend on the file being closed immediately in this case.  If the
> authors of the C implementation ever changed this behavior, they would
> break *lots* of existing python code, and they would also break one of
> the nicest example of how Python just works.
> 

Any existing Python code which depends on the file always being closed here 
is wrong today. If the read method raises an exception the file will not be 
closed until the exception traceback object has been cleared and that could 
be a long time.



More information about the Python-list mailing list