[Tutor] How to open the closed file again?
Kent Johnson
kent37 at tds.net
Tue Jan 5 13:59:11 CET 2010
> 2010/1/5 朱淳 <zhuchunml at gmail.com>:
>> Hi all,
>> I put files in a list, just like this module:
>>
>> #! /usr/bin/python
>> # -*- coding=utf-8 -*-
>>
>>
>> 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
>
> As others have explained, the problem is that you keep adding new file
> objects to fileList. I would make openFiles() return the list of files
> that it opened and pass that as a parameter to closeFiles():
>
> def openFiles():
> fileList = []
> for i in range(0,2):
> fname = "file%s"%i
> f = open(fname,"a")
> fileList.append(f)
> return fileList
>
> def closeFiles(fileList):
> for f in fileList:
> f.close()
>
> if __name__=="__main__":
> fileList = openFiles()
> print fileList
> closeFiles(fileList)
> print fileList
> fileList = openFiles()
> print fileList
>
> Kent
>
More information about the Tutor
mailing list