searchfile = open("file.txt", "r")
for line in searchfile:
if "searchphrase" in line: print line
searchfile.close()
To print out multiple lines (in a simple way)
f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
The comma in print l,
prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.
Or better yet (stealing back from Mark Ransom):
with open("file.txt", "r") as f:
searchlines = f.readlines()
for i, line in enumerate(searchlines):
if "searchphrase" in line:
for l in searchlines[i:i+3]: print l,
print
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…