newbie question: for loop within for loop confusion

John Salerno johnjsal at NOSPAMgmail.com
Mon Jun 16 15:17:24 CEST 2008


"takayuki" <lawtonpaul at gmail.com> wrote in message 
news:a0ff2569-a1a9-44c3-a68a-ee411dcd86eb at g16g2000pri.googlegroups.com...
> fin = open('animals.txt')
>     for line in fin:

You can write this as:

for line in open('animals.txt'):
    #do stuff

Of course, you can't explicitly close the file this way, but that probably 
doesn't matter. Another way, I think, is to wrap the for loops in this:

with open('animals.txt') as file:
    #for loop stuff here 





More information about the Python-list mailing list