user741592
user741592

Reputation: 925

How to count number of lines after a certain line

I am trying to write a code that will count number of lines after certain line. I would like to compute all the lines that appear in my file after {A B} appearing in my file

{A   B}
1     1
0.072 108.815
0.217 108.815
0.362 108.814

My code is as follows:

from __future__ import with_statement
def file_len(fname):
   with open(fname) as f:
        for i, l in enumerate(f):
             pass
   return i + 1

t=file_len("test.ghx")
print t

I am not sure how I can modify this to count the number of lines after specific line that includes {A B}.

Can anyone share some thoughts?

Upvotes: 1

Views: 1263

Answers (2)

vartec
vartec

Reputation: 134601

Count total number of lines in file, check in which line your tag appears, subtract from the total.

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 601669

Skip the lines up to and including the line you are looking for, and count the remaining ones:

def file_len(fname):
    with open(fname) as f:
        for line in f:
            if line.strip() == "{A   B}":
                break
        return sum(1 for line in f)

Upvotes: 4

Related Questions