Python-文件-根据搜索结果更改行号
我需要在调试文件中搜索一个特定的字符串或错误,然后,一旦找到了,就按6行查找该文件,然后打印上面第6行包含的内容Python-文件-根据搜索结果更改行号,python,file,search,line-numbers,Python,File,Search,Line Numbers,我需要在调试文件中搜索一个特定的字符串或错误,然后,一旦找到了,就按6行查找该文件,然后打印上面第6行包含的内容 import linecache file = "/file.txt" fh = open("/file.txt", "r") lookup = 'No Output' with fh as myFile: for num, line in enumerate(myFile, 1): if lookup in line: numUp
import linecache
file = "/file.txt"
fh = open("/file.txt", "r")
lookup = 'No Output'
with fh as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line:
numUp = num + 6
new = linecache.getline(file, numUp)
print new
每当我找到需要搜索的术语时,我尝试添加并执行num+=6的操作,但我的输出为空或收到以下错误:
File "testRead.py", line 12
print new
^
IndentationError: unexpected indent
如果还有另一种方法进行搜索,然后扫描n行,然后以逐行打印/返回的方式进行打印/返回,这也很好,因为我将处理的文件大小差异很大
我提供了一个我通常看到的一些东西的示例文件:
每当我点击字符串Err:No Output时,我都需要找到它的相关ID,即错误上方的6行。所以没有输出是我需要搜索的
::编辑::您想要一个deque的功能:
正如本文所示,缩进是正确的,代码运行正常。检查您的源文件:您可能有空格和制表符混合或一些这样微妙的格式问题。但是,由于file.txt中的第num+6行为空,因此代码不会生成任何输出。我怀疑您可能需要第num+5行。
>>> from collections import deque
>>>
>>> lines = deque(maxlen = 7)
>>> for i in range(35):
... lines.append(i)
...
>>> print lines
# Note your 6 lines earlier would be lines[0] here.
deque([28, 29, 30, 31, 32, 33, 34], maxlen=7)