How to get the previous line in a file?

Shane Geiger sgeiger at ncee.net
Fri Mar 16 16:51:49 EDT 2007


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/toolbar/features/mail/> 
> alerts you the instant new Mail arrives. Check it out. 
> <http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolbar/features/mail/>

-- 
Shane Geiger
IT Director
National Council on Economic Education
sgeiger at ncee.net  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-------------- next part --------------
A non-text attachment was scrubbed...
Name: sgeiger.vcf
Type: text/x-vcard
Size: 310 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20070316/1cbbc8db/attachment.vcf>


More information about the Python-list mailing list