Iterate through dictionary of file objects and file names

Discussion in 'Python' started by Julian Yap, Feb 12, 2005.

  1. Julian Yap

    Julian Yap Guest

    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
    Julian Yap, Feb 12, 2005
    #1
    1. Advertising

  2. Julian Yap

    Brian Beck Guest

    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
    Brian Beck, Feb 12, 2005
    #2
    1. Advertising

  3. Julian Yap

    Julian Yap Guest

    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
    Julian Yap, Feb 13, 2005
    #3
  4. Julian Yap

    Brian Beck Guest

    jfj wrote:
    > Call me a pedant, but what'd wrong with:
    >
    > print 'closed: ' + filename
    > or
    > print 'closed:', filename
    >
    > ?


    I always figure that debug-oriented output like that in example code is
    very likely to be changed in format, or to include more information, by
    the person actually using it. So string substitution makes it more
    flexible; less work for them.

    --
    Brian Beck
    Adventurer of the First Order
    Brian Beck, Feb 13, 2005
    #4
  5. Julian Yap

    jfj Guest

    Brian Beck wrote:
    > print "Closed: %s" % fileName


    Call me a pedant, but what'd wrong with:

    print 'closed: ' + filename
    or
    print 'closed:', filename

    ?

    Modulus operator good but don't over-use it. Otherwise, bad style.


    jfj
    jfj, Feb 13, 2005
    #5
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jansenh
    Replies:
    5
    Views:
    354
    Carl Banks
    Dec 18, 2006
  2. wswilson
    Replies:
    4
    Views:
    318
    Maric Michaud
    Apr 19, 2007
  3. jansenh
    Replies:
    2
    Views:
    80
    David Vallner
    Dec 16, 2006
  4. Skye Weir-mathewes
    Replies:
    3
    Views:
    123
    Stefano Crocco
    Apr 17, 2007
  5. me
    Replies:
    7
    Views:
    114
    yermej
    Mar 16, 2008
Loading...

Share This Page