Nested loop not working

Dave Angel davea at ieee.org
Fri Jul 16 11:29:23 EDT 2010


Johann Spies wrote:
> I am overlooking something stupid.
>
> I have two files: one with keywords and another with data (one record per line).
>
> I want to determine for each keyword which lines in the second file
> contains that keyword.
>
> The following code is not working.  It loops through the second file
> but only uses the first keyword in the first file.
>
> #!/usr/bin/env python
> # -*- coding: utf-8 -*-
>
> import re
>
> keywords = open("sleutelwoorde",'r')
> data = open("sarua_marine_sleutelwoorde.csv",'r')
>
> remove_quotes = re.compile('"')
>
>
> for sw in keywords:
>     for r in data:
>         swc = remove_quotes('',sw)[:-1]
>         if swc in r.lower():
>                 print swc + ' ---> ' + r
>                 print swc
>
> What am I missing?
>
> Regards
> Johann
>
>   
Once you've read all the data from 'data' in the first inner loop, 
there's no more for the second keyword.

Easiest answer is to do something like:
     data.seek(0)
just before the inner loop.  That will (re)position to begin of hte 
'data' file.

DaveA




More information about the Python-list mailing list