[Tutor] How to open the closed file again?

Dave Angel davea at ieee.org
Tue Jan 5 12:31:51 CET 2010


Alan Gauld wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">
> "朱淳" <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.
>
You could probably just open it again, with:

f = open(f.name, f.mode)


This gives you a new object, which looks like the original one. Notice 
that you still have to remove the old object. But that happens 
automatically, if you bind the new object to the same name as the old, 
or to the same list location. So you could write a reopenfiles() 
function, like (untested):

def reopenfiles(fileList):
    for i, f in enumerate(fileList):
        f = open(f.name, f.mode)
        fileList[i] = f


DaveA


More information about the Tutor mailing list