what happens when the file begin read is too big for all lines to be read with "readlines()"

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sat Nov 19 23:00:17 EST 2005


On Sun, 20 Nov 2005 11:05:53 +0800, Xiao Jianfeng wrote:

>  I have some other questions:
> 
>  when "fh" will be closed?

When all references to the file are no longer in scope:

def handle_file(name):
    fp = file(name, "r")
    # reference to file now in scope
    do_stuff(fp)
    return fp


f = handle_file("myfile.txt)
# reference to file is now in scope
f = None
# reference to file is no longer in scope

At this point, Python *may* close the file. CPython currently closes the
file as soon as all references are out of scope. JPython does not -- it
will close the file eventually, but you can't guarantee when.

>  And what shoud I do if I want to explicitly close the file immediately 
> after reading all data I want?

That is the best practice.

f.close()


-- 
Steven.




More information about the Python-list mailing list