Search code examples
pythonnumbersline

Python - Find line number from text file


I'm writing code that looks in a text file, and sees if the input is in there.

E.g.,

I input "pizza"

My textfile contains:

bread
pizza
pasta
tomato

Is there a way to print the line number the word pizza is on?


Solution

  • with open('test.txt') as f:
        content = f.readlines()
    
    index = [x for x in range(len(content)) if 'pizza' in content[x].lower()]
    

    Part (1) of the code reads each line as a separate list in variable "content".

    Part (2) populates out the line # of content only if 'pizza' exists in that line. [x for x in range(len(content))] simply populates all index values, while 'if 'pizza' in content[x].lower()' keeps the line # that matches the string.