Open a List of Files

Tim Chase python.list at tim.thechases.com
Tue Jan 8 21:41:20 EST 2008


> 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')


Another way to write this which reduces some of the code would be

  filenames = ['messages', 'deliveries', 'actions', 'parts',
    'recipients', 'viruses', 'esp_scores']

  (messages, deliveries, actions, parts,
    recipients, viruses, esp_scores) = [
    open(os.path.join(host_path, '%s.txt' % fn), 'wb')
    for fn in filenames
    ]


It becomes even more clear if you make an intermediate "opener"
function such as

  binwriter = lambda fname: open(
      os.path.join(host_path, '%s.txt' % fname), 'wb')

  (messages, deliveries, actions, parts,
    recipients, viruses, esp_scores) = [
    binwriter(fn) for fn in filenames]

This makes it easier to change intended functionality in one
place, rather than updating each line.  Additionally, it's easy
to add a new entry (just add the filename in the filename list,
and the variable-name in the assignment tuple).  It also makes it
clear that each one is getting the same treatment (that there's
not some outlier making you study matters carefully to figure out
that there isn't).

-tkc






More information about the Python-list mailing list