473,756 Members | 2,383 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.1 1", fileBuild: "build.11"}

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

....

# Close optionally open files
for key, optionalFile in optionalFiles.i teritems():
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(optionalFil e)
optionalFile.cl ose()

---< END >---

Thanks,
Julian
Jul 18 '05 #1
4 3644
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.i teritems():
if fileObject:
fileObject.clos e()
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.i teritems():
if fileObject:
fileObject.clos e()
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
3849
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 time error 76. The paths are valid. I tested them and there is a file with the extension specified. Any help is appreciated Marcelo Rizzo
15
2636
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 lists to have duplicate strings when it is avoidable. I have a function createEdge that adds an edge to the graph. The arguments will be distinct since they are read from text files. But basically I want to use the dictionary as a string pool,...
8
4909
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 that objects which compare equal have the same hash value." 3. "If a class does not define a __cmp__() method it should not define a __hash__() operation either."
8
1898
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 tool either with a flat commandline entry like you would a debugger or with a script using scoping, loops and conditional. I am going from knowing nothing about python to almost nothing so the learning curve is rather
4
3357
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 argument. I cannot pass a dictionary that has more keys than the function has arguments. # Example 1 - This works: # Prints "hello world!" def foo (arg1='greetings', arg2='planet', arg3='.'):
70
27495
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 (i.e. 'Banana')?
4
3548
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 object. Then I want to change an objects state based on its key. The way I am doing this now is by using 'fromkeys' and copying my object over in a temporary dictionary, then manipulating the object, and then I do an 'update' back to the main...
14
2111
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 checkbox, since
3
1494
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 .... .... return "f1" + arg ....
0
9456
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9275
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10034
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9872
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5142
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2666
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.