问题
I have been browsing stack overflow for ages now and could not find a solution to this. I need to find a string in a txt file, and then print which line that string was found on. Being the idiot I am, I could not figure this out myself, and I could not find an answer here. And thus, I need a snippet that can do this. I am using Python 2.7.
回答1:
In Python, enumerate is handy for this sort of thing:
with open(myfile) as f:
for index, line in enumerate(f, 1):
if s in line:
print("'{0}' found on line {1}".format(s, index))
来源:https://stackoverflow.com/questions/21357132/python-find-string-in-a-file-and-print-which-line-it-was-found-on