Iterate through dictionary of file objects and file names

Julian Yap jyap80 at gmail.com
Sat Feb 12 20:03:45 EST 2005


Brian Beck wrote:
> 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

Brain,
Thanks for your help.  I never thought of it like that.

I guess in my original thinking, in the processing of the optional files 
I would start off each code block with something like:

if fileAreaCode:
     ...

But now I can just do:
if optionalFiles['areacode.11']:
     ...

I think I was just too much in the above mindset to think clearly about 
the dictionary.

Using a file object as a key!?  What was I thinking :P

Julian



More information about the Python-list mailing list