Using xreadlines

Chris Rebert clp2 at rebertia.com
Thu Feb 26 19:46:22 EST 2009


On Thu, Feb 26, 2009 at 4:32 PM, Brett Hedges <lilhedges69 at yahoo.com> wrote:
>
> Hi,
>
> I am using both xreadlines and files iterators for a script that I need to finish. I am iterating over the entire file but stopping to use xreadlines to grab certain lines as strings to process them.
>
> My question is how do I go to a previous line in the file? xreadlines has a file.next() statement that gives the next line, and I need a statement that gives me the previous line.
>
> My script has a loop that looks for a certain word then breaks the loop. But I need to go to the previous line before I break since the script uses that line (which gets processed). I'm sure there is an easier way to do this but since I am new to python and have spent a lot of time on this script I can't really go back and change a lot of things unless there is no possible way. Something like the example below.
>
> f.open("text.txt",'r')
> files = f.xreadlines()
> Name = "Section 1"
>
>
prev_line = None
> for line in f:
>   if Name in line:
>     while x<20
>       field = files.next()
>         if "2.6" in field:
            use(prev_line)
>      *****files.previousline()*****
>           break
    prev_line = line
>     x=x+1

Also, you could probably make the loop prettier by using enumerate()
or range() to track `x`.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list