Anonymous file closing

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

surferjeff at (Jeff) wrote in
news:781dd16f.0406111108.6f2e1afd at 
>> > 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