Iterate through dictionary of file objects and file names

Julian Yap jyap80 at gmail.com
Sat Feb 12 06:40:09 EST 2005


Hi all,
I'm trying to get some ideas on the best way to do this.

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.

---< CODE FOLLOWS >---
optionalfiles = {fileAreaCode: "areacode.11", fileBuild: "build.11"}

# Try to see if optional file exists, if so, open.
try:
     for key, optionalFile in optionalFiles.iteritems():
         key = open(optionalFile, "r")
except IOError:
     key = False

...

# Close optionally open files
for key, optionalFile in optionalFiles.iteritems():
     if optionalFile:
         print "Closing: %s" % optionalFile
         key.close()

---< END CODE >---

My questions are:
Is this even possible in a dictionary to have a key of a file object?
If so, how do I initialise an empty file object?  I mean, something 
along the lines of:
fileAreaCode = open("", "r")
If not, any suggestions on achieving openning optional files in a loop? 
  Otherwise I'm stuck with:

---< BEGIN >---

# Optional input files
try:
     fileAreaCode = open("areacode.11", "r")
except:
     fileAreaCode = False

try:
     fileBuild = open("build.11", "r")
except:
     fileBuild = False

...

# Close files
for optionalFile in [fileAreaCode, fileBuild]:
     if optionalFile:
         print "Closing: %s" % str(optionalFile)
         optionalFile.close()

---< END >---

Thanks,
Julian



More information about the Python-list mailing list