Open a List of Files

Chris cwitts at gmail.com
Tue Jan 8 07:04:01 EST 2008


On Jan 8, 1:03 pm, Fredrik Lundh <fred... at pythonware.com> wrote:
> BJ Swope 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.
>
> the code looks ok.  please define "not working".
>
> </F>

Bad coding style in that one.  Do you have Write permissions to that
'Host_path' ?

import os, sys

FILELIST = ['messages', 'recipients', 'viruses']
HOST_PATH = os.getcwd()  # Or whatever path you are using

if not os.access(HOST_PATH, os.W_OK):
    sys.exit('Unable to write to path specified.')

for file in FILELIST:
    output_file = open(os.path.join(HOST_PATH, file), 'wb')
    do_something_with_file()


A better definition of not working would be appreciated, Tracebacks if
you have.



More information about the Python-list mailing list