Open a List of Files

BJ Swope bigblueswope at gmail.com
Wed Jan 9 00:40:56 EST 2008


On Jan 8, 2008 9:34 PM, Terry Jones <terry at jon.es> wrote:

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


Thanks for the advice Terry.  With your prompting I went back and looked at
the examples and sought to understand them.

The results are...

#File Creations/Openings
def getfilename(host_path, fn):
    return os.path.join(host_path, '%s.txt' % fn)

outfiles_list = ['messages', 'deliveries', 'actions', 'parts', 'recipients',
'viruses', 'esp_scores']
open_files = {}
for fn in outfiles_list:
    open_files[fn] = open(getfilename(host_path, fn), 'wb')


#Referring to files to write in various places...
open_files['deliveries'].write(flat_line)
open_files['deliveries'].write('\n')


#And finally to close the opened files
for fn in open_files.keys():
    open_files[fn].close()


I sure am glad I posted this to the list.  It is exactly the kind of stuff I
was hoping to find.

Again, to all who answered, Thank You!


BJ
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080109/fcc81de4/attachment.html>


More information about the Python-list mailing list