[Tutor] How to open the closed file again?

Alan Gauld alan.gauld at btinternet.com
Tue Jan 5 09:46:59 CET 2010

"朱淳" <zhuchunml at gmail.com> wrote

> fileList = []
> def openFiles():
>    for i in range(0,2):
>        fname = "file%s"%i
>        f = open(fname,"a")
>        fileList.append(f)
> def closeFiles():
>    for f in fileList:
>        f.close()
> if __name__=="__main__":
>    openFiles()
>    print "fileList
>    closeFiles()
>    print fileList
>    openFiles()
>    print fileList
>    I found that after closing files some closed files were left in the
> list:

Yes, because you never remove them they will stay there.
If you want to remove them from the list you need you del() them
as part of your close method.

>   After I call openFiles() and closeFiles() many times, the list will
> become fatter and fatter, filled with valueless closed file object. How
> could I open the closed file? I can't find the way in python document.

I don't know of a way to open a closed file object, you might want
to store the filename along with the file. Then if you discover it is
closed you can use the name to reopen it.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list