【问题标题】:Python - Files - Changing line numbers based on search resultsPython - 文件 - 根据搜索结果更改行号
【发布时间】:2014-09-26 00:28:53
【问题描述】:

我需要在调试文件中搜索特定字符串或错误,然后,一旦找到,查找文件的 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 = num + 6
            new = linecache.getline(file, numUp)        
            print new

每当我发现“我需要搜索的术语”时,我尝试添加一些类似“num += 6”的内容,但我的输出要么为空白,要么收到此错误:

File "testRead.py", line 12
    print new
    ^
IndentationError: unexpected indent

如果还有另一种方法可以逐行进行“搜索,然后扫描 n 行,然后打印/返回”,那也很高兴知道,因为我将要处理的文件大小差别很大。

我增加了一些我通常看到的东西的示例文件:http://pastebin.com/mzvCfZid 每当我点击字符串“(Err: No Output)”时,我都需要找到它的关联 ID,即错误上方的第 6 行。所以“没有输出是我需要搜索的。

::编辑::

【问题讨论】:

  • 正如这里展示的那样,缩进是正确的并且代码可以运行。检查您的源文件:您可能混合了空格和制表符或一些此类微妙的格式问题。但是,该代码不会生成任何输出,因为 file.txt 中的行 num+6 是空白的。我怀疑你可能想要num+5 行。

标签: python file search line-numbers


【解决方案1】:

您想要deque 的功能:

>>> 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) 

【讨论】:

    猜你喜欢
    • 2011-06-08
    • 1970-01-01
    • 2019-03-11
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多