John J. Lee jjl at
Thu Aug 21 00:24:05 CEST 2003

David Bear <david.bear at> writes:

> I was in a hurry to do something and I did
> stuff = open("filename", "r").read()
> then I realized, "hey I didn't close the file".
> so python close it automagically?  Since I was doing python
> interactively I expect the interpreter closed the file for me but my
> guess is the above syntax is probably poor.  any comments?

Yes, the file gets closed when the file object gets garbage collected
by Python, but explicitly closing it is a good idea, especially when
writing to a file (since your OS might not save you from lost data if
your program exits without closing the file) and when there's any
chance your code might be run on Jython (because Java will
garbage-collect your file at some random time, which may break your

The fact that the file got closed automatically has nothing to do with
the fact that you were using the interactive prompt.


More information about the Python-list mailing list