[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Open a List of Files

Neil Cerutti

1/8/2008 12:07:00 PM

On Jan 8, 2008 6:54 AM, BJ Swope <bigblueswope@gmail.com> wrote:
> > > given a list such as
> > >
> > > ['messages', 'recipients', 'viruses']
> > >
> > > how would I iterate over the list and use the values as variables and
> > > open the variable names a files?
> > >
> > > I tried
> > >
> > > for outfile in ['messages', 'recipients', 'viruses']:
> > > filename = os.path.join(Host_Path, outfile)
> > > outfile = open(filename, 'w')
> > >
> > > But it's not working.
>
> Yep, defining "not working" is always helpful! :)
>
> I want to have all 3 files open at the same time. I will write to each of
> the files later in my script but just the last file is open for writing.

Your code successfully opened them all, but kept a reference only to
the last one.

Try something like:

outfiles = [open(os.path.join(Host_Path, fname), 'w') for fname in fnames]

--
Neil Cerutti <mr.cerutti+python@gmail.com>