[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

Fredrik Lundh

1/8/2008 11:04:00 AM

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>

2 Answers

John Machin

1/8/2008 11:31:00 AM

0

On Jan 8, 10:03 pm, Fredrik Lundh <fred...@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".
>

To me, it looks bad. He's rebinding "outfile" inside the loop, which
is not good style, makes the reader slow down, back up, read the code
again ... however this doesn't stop this small code fragment from
opening the 3 files for write access -- assuming an import, and
suitable contents for "Host_Path".

Chris

1/8/2008 12:04:00 PM

0

On Jan 8, 1:03 pm, Fredrik Lundh <fred...@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.