will it cause any problems to open a read-only file & not close it?

Terry Reedy tjreedy at udel.edu
Tue Mar 15 01:44:10 CET 2005

"Sara Khalatbari" <sarapythonlist at yahoo.com> wrote in message 
news:20050314121355.37947.qmail at web61108.mail.yahoo.com...

> In a code, I'm opening a file to read. Like :
>    lines = open(filename).readlines()
> & I'm never closing it.
> I'm not writing in that file, I just read it.

Since you do not save a reference to the file object, it is eligible for 
deletion (which causes file closure).  This will happen immediately in 
CPython, maybe sometime before the program exits in Jython, and certainly 
when the program exits.

> Will it cause any problems if you open a file to read
> & never close it?

If you keep a file open either with a reference or by use of Jython, other 
processes that want to use the file can have a problem.  If you try to keep 
more files open the the operating system allows, the next open() call will 
fail.  But for typical programs in typical system usage, you should not 
have a problem.  Many do the same as you.  Others think it bad programming. 
Take your pick.

Terry J. Reedy

More information about the Python-list mailing list