[Tutor] Searching in a file
Emile van Sebille
emile at fenx.com
Wed Jan 13 21:39:02 CET 2010
On 1/13/2010 9:49 AM Paul Melvin said...
> Hi,
>
> I have a file generated from a webpage.
>
> I want to search that file for a specific keyword, in my case 'NEW'.
>
> Once I have found that keyword I want to retrieve information below it, e.g.
> web link, size of file etc.
>
> When I have this information I move off until I find another 'NEW' and the
> process starts all over.
>
> Please can someone give me some pointers on how to do this.
>
> I can find the line containing 'NEW' which I get using a simple for loop on
> every line in the file, but how do I then traverse the next x amount of
> lines, taking what I want until either the next 'NEW' or eof.
>
> e.g.
>
> for line in file:
> if re.findall('NEW', line) # or search
> list.append(line) # to do something to later
<don't use list as i shadows the builtin list>
>
> I cannot 'get' to the following lines because I would need to get out of the
> loop.
How about (untested):
additionalLines = 3
remainingLines = 0
for line in file:
if 'NEW' in line or remainingLines:
mylist.append(line)
if not remainingLines:
remainingLines = additionalLines
else:
remainingLines -= 1
Emile
>
> I did use enumerate and was wondering if I could use the line number, or
> maybe I could use an re iterator.
>
> Any advice would be much appreciated.
>
> Thanks
>
> paul
>
>
> __________ Information from ESET Smart Security, version of virus signature
> database 4767 (20100113) __________
>
> The message was checked by ESET Smart Security.
>
> http://www.eset.com
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list