Open a List of Files

Terry Jones terry at jon.es
Tue Jan 8 21:34:07 EST 2008


Hi BJ

> > Fredrik Lundh <fredrik at pythonware.com> writes:
> > Or in a dict:
> >
> > open_files = {}
> > for fn in ['messages', 'recipients', 'viruses']:
> >    open_files[fn] = open(getfilename(fn), 'w')
> 
> I decided that I was just trying to be "too smooth by 1/2" so I fell back
> to ...
> 
> 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,'actions.txt'), 'wb')
> parts = open(os.path.join(host_path,'parts.txt'), 'wb')
> recipients = open(os.path.join(host_path,'recipients.txt'), 'wb')
> viruses = open(os.path.join(host_path,'viruses.txt'), 'wb')
> esp_scores = open(os.path.join(host_path,'esp_scores.txt'), 'wb')

I think you should revisit this decision.  Something like Fredrik's code is
the way to go.  It has multiple advantages:

 - It's much shorter.
 - It's arguably easier to add/remove to/from.
 - It has less risk of error (much less repetition).
 - 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.
 - You can close all open files with a trivial loop.

Also, if you start writing code like Fredrik's instead of like what you
fell back on you'll make yourself a better programmer (in general, not just
in Python).

Terry



More information about the Python-list mailing list