There are two ways of accomplishing this:
- Storing the entire file in memory so you only read it once
- 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