Search code examples
pythonfiletextexternal

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

Solution

  • 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