Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.x : move to next line

I've got a small script that is extracting some text from a .html file.

f = open(local_file,"r")
for line in f:
    searchphrase = '<span class="position'
    if searchphrase in line:
        print("found it\n")

That works fine for me(error handling will be imported later), my problem is that the text I want to extract follows 2 lines after the searchphrase. How can I move 2 lines down in the .html file ?

like image 955
SaintCore Avatar asked Mar 27 '13 10:03

SaintCore


1 Answers

You can advance f (which is an iterable) by two lines by calling next() on it twice:

with open(local_file,"r") as f
    for line in f:
        searchphrase = '<span class="position'
        if searchphrase in line:
            print("found it\n")
            next(f) # skip 1 line
            return next(f)  # and return the line after that.

However, if you are trying to parse HTML, consider using a HTML parser instead. Use BeautifulSoup, for example.

like image 158
Martijn Pieters Avatar answered Oct 11 '22 14:10

Martijn Pieters