473,386 Members | 1,721 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Iterate through dictionary of file objects and file names

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
Jul 18 '05 #1
4 3626
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
Jul 18 '05 #2
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
Jul 18 '05 #3
jfj
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
Jul 18 '05 #4
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
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Marcelo Rizzo | last post by:
I am trying to get the name of a file with a specific extension (tmw) from several different directories. The problem I am having is that the program stops working on the second pass with an run...
15
by: Andy C | last post by:
I am new to python, so please bear with me if I am making some conceptual error. Basically I want to create a graph with an adjacency list representation, but I don't want any of the adjacency...
8
by: Jan-Erik Meyer-Lütgens | last post by:
In the Python Language Reference, I found the following statements about using objects as dictionary keys: 1. "__hash__() should return a 32-bit integer." 2. "The only required property is...
8
by: Jack Carter | last post by:
I have been delegated to produce a tool that has python embedded in it. The desire is to have a command line interface that inherits all the python scripting functionality so people can use the...
4
by: Noah | last post by:
I have a dictionary that I would like to expand to satisfy a function's agument list. I can used the ** syntax to pass a dictionary, but this only works if each key in the dictionary matches an...
70
by: jojoba | last post by:
Hello! Does anyone know how to find the name of a python data type. Conside a dictionary: Banana = {} Then, how do i ask python for a string representing the name of the above dictionary...
4
by: jansenh | last post by:
hi comp.lang.python. I need some newbe advice on idiomatic use of Python dictionaries. I have service with a dictionary which holds a bunch of objects as values, and an ID as key to each...
14
by: tdahsu | last post by:
I have twenty-five checkboxes I need to create (don't ask): self.checkbox1 = ... self.checkbox2 = ... .. .. .. self.checkbox25 = ... Right now, my code has 25 lines in it, one for each...
3
by: mk | last post by:
Hello everyone, I'm storing functions in a dictionary (this is basically for cooking up my own fancy schmancy callback scheme, mainly for learning purpose): .... return "f2 " + arg .......
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.