BlueCanary
BlueCanary

Reputation: 67

Find the line number a string is on in an external text file

I am trying to create a program where it gets input from a string entered by the user and searches for that string in a text file and prints out the line number. If the string is not in the text file, it will print that out. How would I do this? Also I am not sure if even the for loop that I have so far would work for this so any suggestions / help would be great :).

What I have so far:

file = open('test.txt', 'r')
string = input("Enter string to search")
for string in file:
    print("") #print the line number

Upvotes: 2

Views: 8000

Answers (4)

catsock
catsock

Reputation: 1851

A text file differs from memory used in programs (such as dictionaries and arrays) in the manner that it is sequential. Much like the old tapes used for storage a long, long time ago, there's no way to grab/find a specific line without combing through all prior lines (or somehow guessing the exact memory location). Your best option is just to create a for loop that iterates through each line until it finds the one it's looking for, returning the amount of lines traversed until that point.

file = open('test.txt', 'r')
string = input("Enter string to search")
lineCount = 0
for line in file:
    lineCount += 1
    if string == line.rstrip(): # remove trailing newline
        print(lineCount)
        break

Upvotes: 0

Joe Iddon
Joe Iddon

Reputation: 20414

If the string will match a line exactly, we can do this in one-line:

print(open('test.txt').read().split("\n").index(input("Enter string to search")))

Well the above kind of works accept it won't print "no match" if there isn't one. For that, we can just add a little try:

try:
    print(open('test.txt').read().split("\n").index(input("Enter string to search")))
except ValueError:
    print("no match")

Otherwise, if the string is just somewhere in one of the lines, we can do:

string = input("Enter string to search")
for i, l in enumerate(open('test.txt').read().split("\n")):
    if string in l:
        print("Line number", i)
        break
else:
    print("no match")

Upvotes: 0

janos
janos

Reputation: 124646

You can implement this algorithm:

  • Initialize a counter
  • Read lines one by one
  • If the line matches the target, return the current count
  • Increment the count
  • If reached the end without returning, the line is not in the file

For example:

def find_line(path, target):
    with open(path) as fh:
        count = 1
        for line in fh:
            if line.strip() == target:
                return count
            count += 1

    return 0

Upvotes: 1

Dvir Samuel
Dvir Samuel

Reputation: 1168

filepath = 'test.txt'
substring = "aaa"
with open(filepath) as fp:  
   line = fp.readline()
   cnt = 1
   flag = False
   while line:
       if substring in line:
            print("string found in line {}".format(cnt))
            flag = True
            break
       line = fp.readline()
       cnt += 1
   if not flag:
       print("string not found in file")

Upvotes: 0

Related Questions