Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Find line number from text file [closed]

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?

like image 783
googlecoolcat Avatar asked Jan 02 '17 16:01

googlecoolcat


2 Answers

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.

like image 168
Oxymoron88 Avatar answered Nov 14 '22 04:11

Oxymoron88


There are two ways of accomplishing this:

  1. Storing the entire file in memory so you only read it once
  2. Reading through the file on every search, but not having to store it

For method 1, first read in every line and then get the index that the word is on:

with open('path.txt') as f: data = f.readlines()
line_no = data.index("pizza")

Alternatively, go through the file to find the index:

with open('path.txt') as f:
    for line_no, line in enumerate(f):
        if line == "pizza":
            break
    else: # for loop ended => line not found
        line_no = -1
like image 20
Rushy Panchal Avatar answered Nov 14 '22 04:11

Rushy Panchal