searchfile = open("file.txt", "r")for line in searchfile: if "searchphrase" in line: print linesearchfile.close()
打印出多行(以一种简单的方式)
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
print l,防止输出中出现多余的空格。尾随的打印语句将结果划分为不同的行。
或者更好(从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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)