a simple 'for' question

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Jul 9 07:52:45 EDT 2008


Tim Cook a écrit :
> On Wed, 2008-07-09 at 00:00 -0400, Ben Keshet wrote:
>> oops, my mistake, actually it didn't work...
>> when I tried:
>> for x in folders:
>>     print x     # print the current folder
>>     filename='Folder/%s/myfile.txt' %x
>>     f=open(filename,'r')
>>
>> it says: IOError: [Errno 2] No such file or directory:
>> 'Folder/1/myfile.txt'
>>
> 
> I believe it's because x is the position marker what you want instead is
> the contents of folders at x; therefore folders[x] 

Nope. Python's for loops iterate over elements, not over indices. Here, 
the following code:

folders= ['1A28','1A6W','56Y7']
for x in folders:
    print x
    filename='Folder/%s/myfile.txt' %x
    print filename

yields:

1A28
Folder/1A28/myfile.txt
1A6W
Folder/1A6W/myfile.txt
56Y7
Folder/56Y7/myfile.txt

IOW: the problem is elsewhere.




More information about the Python-list mailing list