Open a List of Files

Fredrik Lundh fredrik at pythonware.com
Wed Jan 9 02:51:06 EST 2008


Terry Jones wrote:

> I think you should revisit this decision.  Something like Fredrik's code is
> the way to go.

He used my suggestion, just for a few more files than he had in his 
original post.

Seriously, for a limited number of files, the dictionary approach is 
mostly pointless; you end up replacing

     foo = open("foo")
     foo.write(...)

with

     somedict["foo"] = open("foo")
     somedict["foo"].write(...)

which, frankly, sucks in a whole lot of ways.

>  It has multiple advantages:
> 
>  - It's much shorter.

For a small number of files, it isn't, really.

>  - It's arguably easier to add/remove to/from.

Only if you're not using the files you're opening; as soon you try to do 
something with them, it's more work.

>  - It has less risk of error (much less repetition).

No, it hasn't.  There's more to type when using the files, and you have 
*two* things you can misspell; that is, you're replacing a NameError 
with either a NameError or a KeyError.

>  - It allows your code to later take a string file tag and
>    write to that file by looking up its file descriptor in the dict.

Instead of allowing your code to take a file object and write to that 
file by writing to that file object?

>  - You can close all open files with a trivial loop.

Ok, this is actually an advantage.  Not that you need to do that very 
often, since Python does it for you.  And if you find yourself needing 
to do this a lot, you can of course stuff all the output files in a list 
but *still* use the variables to refer to the file when writing to them.

:::

There is one case where a dictionary of files makes perfect sense, of 
course, and that's when you can associate the file with some *other* 
value that you're *already* using. (Say, a user name or a machine name 
or a severity level or something like that.)  But inventing your own 
string tags to use instead of variables is just plain bad design.

</F>




More information about the Python-list mailing list