lamwaiman1988
lamwaiman1988

Reputation: 3742

find a matching line in a txt with python

I can test whether a string is in a text file with python like the following:

if(pdfname in open(filename).read()):
   //do something

But how I can I verify it? I want the matching line show up. Thanks.

Upvotes: 2

Views: 196

Answers (2)

paxdiablo
paxdiablo

Reputation: 881153

You can print out the relevant lines with the second for statement below, which I've added to your existing code for illustration:

pdfname = "statementConcentrator"
if (pdfname in open("line56.good").read()):
    print "Found it"

lineNum = 0
for line in open("line56.good").readlines():
    lineNum = lineNum + 1
    if pdfname in line:
        print "#%5d: %s"%(lineNum, line[:-1])

This outputs your current line plus my output for verification:

Found it
#  115:  statementConcentrator=0

and, checking that file, that is indeed the line it's found on.

Note that you can simply use a script as follows to do both jobs in a single loop:

pdfname = "statementConcentrator"
lineNum = 0
count = 0
for line in open("line56.good").readlines():
    lineNum = lineNum + 1
    if pdfname in line:
        print "#%5d: %s"%(lineNum, line[:-1])
        count = count + 1
print "Found on %d line(s)."%(count)

Upvotes: 1

Blender
Blender

Reputation: 298106

Just loop over the file:

handle = open(filename, 'r')

for line in handle:
  if pdfname in line:
    print line

handle.close()

Upvotes: 2

Related Questions