Open a List of Files

Terry Jones terry at jon.es
Wed Jan 9 09:25:28 EST 2008


>>>>> "Fredrik" == Fredrik Lundh <fredrik at pythonware.com> writes:

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

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

Fredrik> with

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

Yes, in some cases. But where you want to do multiple things you can always
pull the file descriptor of of the dict into a local var.

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

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

Well I meant less error risk in the context of opening the files. And I'm
happy to get a NameError or KeyError if I make the mistake you describe.
But bad code like this:

    messages = open(os.path.join(host_path,'messages.txt'), 'wb')
    deliveries = open(os.path.join(host_path,'deliveries.txt'), 'wb')
    actions = open(os.path.join(host_path,'deliveries.txt'), 'wb')

doesn't give an error at all, and with all that identical and
semi-identical code it's much less obvious where the error is.

Cut & paste errors like this are pretty common, and they can be quite hard
to find (when they don't result in exceptions), in my experience.

>> - 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.

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

No, see below:

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

Fredrik> Ok, this is actually an advantage.  Not that you need to do that very 
Fredrik> often, since Python does it for you.

Yes.  That's partly why I said it would make him a better programmer in
general, not just in Python.

Fredrik> And if you find yourself needing to do this a lot, you can of
Fredrik> course stuff all the output files in a list but *still* use the
Fredrik> variables to refer to the file when writing to them.

Yes, as above.

Fredrik> There is one case where a dictionary of files makes perfect sense, of 
Fredrik> course, and that's when you can associate the file with some *other* 
Fredrik> value that you're *already* using. (Say, a user name or a machine name 
Fredrik> or a severity level or something like that.)

Yes. That's what I meant by my original - badly worded - remark (see above)
that you could take a "string file tag" and use it to look up its file
descriptor.

Terry



More information about the Python-list mailing list