leanne
leanne

Reputation: 121

how to find the line number where specific text exists?

This question is about how to find the line number where specific text for example "this is my horse" exists?

text file:

this is my name
this is my address
this is my age
this is my horse
this is my book
this is my pc

my code:

with open ('test.txt', 'r') as infile:
 ?????

Upvotes: 1

Views: 95

Answers (3)

user1129665
user1129665

Reputation:

You can do something like this:

with open ('test.txt', 'r') as infile:
    data = infile.readlines()
    for line, content in enumerate(data, start=1):
            if content.strip() == 'this is my horse':
                print line

which in case of your file will print:

4

Upvotes: 1

alecxe
alecxe

Reputation: 473813

s = "this is my horse"
with open ('test.txt', 'r') as infile:
    print next(index for index, line in enumerate(infile, start=1) if line.strip() == s)

prints 4.

Note, that you need to apply strip() on lines in order to get rid of new-line chars at the end.

Upvotes: 1

Henrik Andersson
Henrik Andersson

Reputation: 47172

Use the enumerate function as it works on anything that is an iterable (which your file is).

for line_number, line in enumerate(infile):
  print line_number, line

Upvotes: 2

Related Questions