Iterate through dictionary of file objects and file names

Brian Beck exogen at gmail.com
Sat Feb 12 07:50:48 EST 2005


Julian Yap wrote:
> In this particular coding snippet, I was thinking of creating a 
> dictionary of file objects and file names.  These would be optional 
> files that I could open and parse.  At the end, I would easily close off 
> the files by iterating through the dictionary.

Hi,

File objects as keys sounds pretty dangerous. I'm curious why the first 
thought that popped into your head wasn't using the file NAMES as keys 
instead? Here's my go at it. (Is Google Groups nice to indentation using 
spaces? I can't remember.)

optionalFiles = dict.fromkeys(['areacode.11', 'build.11'], None)

# To open optionalFiles...
for fileName in optionalFiles:
     try:
         optionalFiles[fileName] = open(fileName, "r")
         print "Opened: %s" % fileName
     except IOError:
         # Values are already initialized to None.
         print "File not found: %s" % fileName

# To close optionalFiles...
for fileName, fileObject in optionalFiles.iteritems():
     if fileObject:
         fileObject.close()
         print "Closed: %s" % fileName
         # Rebinding fileObject here won't modify the dictionary,
         # so access it through the key.
         optionalFiles[fileName] = None


--
Brian Beck
Adventurer of the First Order



More information about the Python-list mailing list