【问题标题】:How to read file in line and back to specific line to read it again如何在行中读取文件并返回到特定行以再次读取它
【发布时间】:2021-03-04 18:04:32
【问题描述】:

我正在尝试在文件中查找特定字符串(假设这是条件 1.1),如果找到该字符串,我需要在条件 1.1 字符串之后找到另一个字符串(假设这是条件 1.2)。如果条件 1.2 存在,我需要回到条件 1.1 加一行。并从那里再次读取,以防我找到条件 2.1、3.1、4.1 的字符串。

假设文件是​​这样的

line 1
line 2
condition 1.1
line 4
line 5
line 6
line 7
condition 2.1
line 9
line 10
line 11
condition 2.2
line 12
line 13
condition 1.2

到目前为止,我所做的是使用 f.readline 读取文件行并检查条件 1.1 和 1.2,而不考虑检查条件 2.1 和 2.2。

如何实现这种情况?我想过像 DFS 这样的东西,但我认为打开的 python 文件没有readline before 功能

这是我的伪代码

def beta(f, line):
    if("STRING A Condition 1.1" in line):
        while True:
            if("STRING B Condition 1.2" in line):
                return 1
            if(line is none):
                return None
            line = f.readline() # This is my code problem. it continues the f.readline of the caller.

def alpha():
    with open(file_name, 'r') as f:
        line = f.readline()
        while line:
            value = beta(f, line)
            if(value is not None):
                print("dummy yes")
            line = f.readline()
            if(line is None):
                break

【问题讨论】:

  • 你能改写“如果存在第二个条件,我需要回到条件 1 加上一行并从那里再次读取,以防我找到条件 2.1、3.1、4.1 的字符串。”?尽量使所需的功能尽可能清晰。
  • 好的,编辑成1.1和1.2

标签: python python-3.x algorithm python-2.7 file


【解决方案1】:

考虑使用seektell 来保存和恢复您在文件中的位置。

f.seek(x, y) 将文件f 中的当前位置移动到从y 偏移x 的位置。

f.tell() 返回文件f 中的当前位置。

例如,考虑以下代码:

with open("test.txt") as f:
    saved_place = 0
    line = f.readline()
    while line:
        if "condition 1.1" in line:
            # save your place in the file
            saved_place = f.tell()
            while line:
                if "condition 1.2" in line:
                    # 'rewind' the file
                    f.seek(saved_place, 0)
                    print(f.read())
                line = f.readline()
        line = f.readline()

遇到条件1.1时,可以使用saved_place = f.tell()将该位置保存到文件中,之后使用f.seek(saved_place, 0)将文件中的当前位置恢复到该位置。上面的例子只是打印了从 1.1 到结尾的文件,但是你可以用任何你喜欢的逻辑替换它。

【讨论】:

  • 感谢您的回答,它正在工作。我也想赞成你的答案,但我不能。如果您可以对我的问题进行投票,那就太好了,这样我就可以拥有适当的声誉来投票。顺便说一句,我使用saved_place = f.tell() + 1 使其在f.seek(saved_place, 0) 中工作。所以我不必使用需要字节读取的f.seek(saved_place, 2)
猜你喜欢
  • 2020-02-10
  • 1970-01-01
  • 2011-07-20
  • 2015-05-02
  • 1970-01-01
  • 2017-09-13
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多