How to get the previous line in a file?

Jerry Hill malaclypse2 at gmail.com
Fri Mar 16 17:48:27 EDT 2007


On 3/16/07, Qilong Ren <qilong_ren at yahoo.com> wrote:
> 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?

I would do something like the following:

inFile = open("LICENSE.txt")

prev_line = None
for line in inFile:
    if "foo" in line:
        print prev_line
        print line
    prev_line = line
inFile.close()

-- 
Jerry



More information about the Python-list mailing list