问题
I'm writing a 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
I want to find a way to print the the line number the word pizza is on. Any help?
回答1:
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.
回答2:
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
回答3:
Something like this ?
import re
import os # You can go without is if you have other means to get your filepath
i = 1
matches = []
target = raw_input("Please type string to match\n")
with open(os.getenv("SOME_PATH") + "/myfile.txt") as fic: # open("myfile.txt") if in your current directory
for line in fic:
if re.search(target, line):
print "Found at line {}".format(i)
matches.append(i)
i = i +1
if not len(matches):
raise Exception, "target not found"
By doing this, you can input a regular expression and it should work (i.e. if you input "p.zza" or "^p.*", it will work.). The list matches
will contain all indices of lines that match the input pattern.
回答4:
print next (i for i,v in enumerate (open (fname),1) if v == needle)
来源:https://stackoverflow.com/questions/41429941/python-find-line-number-from-text-file