Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python搜索一个.txt文件,当找到匹配项时,在匹配词后打印若干行_Python - Fatal编程技术网

Python搜索一个.txt文件,当找到匹配项时,在匹配词后打印若干行

Python搜索一个.txt文件,当找到匹配项时,在匹配词后打印若干行,python,Python,我想搜索一个文件,当找到我要找的单词时,我想让它打印该单词下面的8行。请记住,我是一个彻头彻尾的傻瓜,我做这件事才几个星期。这就是我所拥有的,但它不起作用(显然!): lines.index将查找与名称完全相同的行。 您需要遍历这些行并搜索字符串 i = -1 for x, line in enumerate(lines): if line.find(name) != -1: i = x break .... 不确定这是否是您要查找的内容,但如果您的输入

我想搜索一个文件,当找到我要找的单词时,我想让它打印该单词下面的8行。请记住,我是一个彻头彻尾的傻瓜,我做这件事才几个星期。这就是我所拥有的,但它不起作用(显然!):


lines.index将查找与名称完全相同的行。 您需要遍历这些行并搜索字符串

i = -1
for x, line in enumerate(lines):
    if line.find(name) != -1:
        i = x
        break
....

不确定这是否是您要查找的内容,但如果您的输入与文件中某行的内容完全匹配,则代码可能如下所示:

name = input("What did you put as the calculation name?: ")
saved_calcs = open("saved_calcs.txt", "r")
lines = saved_calcs.read()
split_lines = lines.split("\n")
index = split_lines.index(str(name))+1
for line in split_lines[index:index+8]:
    print line
saved_calcs.close()

您可能需要
lines=saved\u calc.readlines()
,这太棒了!谢谢你!
name = input("What did you put as the calculation name?: ")
saved_calcs = open("saved_calcs.txt", "r")
lines = saved_calcs.read()
split_lines = lines.split("\n")
index = split_lines.index(str(name))+1
for line in split_lines[index:index+8]:
    print line
saved_calcs.close()