How to get the previous line in a file?

Paul McGuire ptmcg at austin.rr.com
Fri Mar 16 17:34:31 EDT 2007


On Mar 16, 3:51 pm, Shane Geiger <sgei... at ncee.net> wrote:
> lines = open('/tmp/foo.py',
> "r").read().splitlines()                                                                                                    
>
> previous_line =
> ''                                                                                                                                      
>
> for line in
> lines:                                                                                                                                      
>
>     if "foo" in
> line:                                                                                                                                  
>
>         print "found foo in the current line.  The previous line is:  "
> +
> previous_line                                                                
>
>     previous_line =
> line                                                                                                                                
>
>
>
>
>
> Qilong Ren wrote:
> > Hi,all
>
> > I am new to this list. And I am glade I am here.
> > I have a question. I need to do some text processing. I need to read
> > from a file line by line. If some line is met with some condition, the
> > previous line needs some modification. How to get the info of the
> > previous line?
>
> > Thanks!
> > Qilong
>
> > ------------------------------------------------------------------------
> > Never miss an email again!
> > Yahoo! Toolbar
> > <http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolb...>
> > alerts you the instant new Mail arrives. Check it out.
> > <http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolb...>
>
> --
> Shane Geiger
> IT Director
> National Council on Economic Education
> sgei... at ncee.net  |  402-438-8958  |  http://www.ncee.net
>
> Leading the Campaign for Economic and Financial Literacy
>
>  sgeiger.vcf
> 1KDownload- Hide quoted text -
>
> - Show quoted text -

If the list is not long, zip the lines together in pairs:

lines = """
test1
test2
foo
test3
test4
""".split("\n")

for prev,curr in zip(lines[:-1],lines[1:]):
    if "foo" in curr:
        break
else:
    prev = "<not found>"
print "line before foo is:", prev

prints:
line before foo is: test2

-- Paul




More information about the Python-list mailing list