python - 从特定文本行读取文件

BPm*_*BPm 16 python file linecache

我不是在谈论特定的行号,因为我正在阅读具有相同格式但长度不同的多个文件.
说我有这个文本文件:

Something here...  
... ... ...   
Start                      #I want this block of text 
a b c d e f g  
h i j k l m n  
End                        #until this line of the file
something here...  
... ... ...  
Run Code Online (Sandbox Code Playgroud)

我希望你知道我的意思.我正在考虑迭代文件,然后使用正则表达式搜索,找到"开始"和"结束"的行号,然后使用linecache从开始行读取到结束行.但是如何获得行号?我可以使用什么功能?

Eri*_*got 33

如果您只想在Start和之间使用文本块End,您可以执行以下简单操作:

with open('test.txt') as input_data:
    # Skips text before the beginning of the interesting block:
    for line in input_data:
        if line.strip() == 'Start':  # Or whatever test is needed
            break
    # Reads text until the end of the block:
    for line in input_data:  # This keeps reading the file
        if line.strip() == 'End':
            break
        print line  # Line is extracted (or block_of_lines.append(line), etc.)
Run Code Online (Sandbox Code Playgroud)

实际上,您不需要操作行号就可以读取开始和结束标记之间的数据.

逻辑("读取直到......")在两个块中重复,但它非常清晰和有效(其他方法通常涉及检查某些状态[在块/块内/块到达之前],这会导致时间损失).


orl*_*rlp 5

这是有用的东西:

data_file = open("test.txt")
block = ""
found = False

for line in data_file:
    if found:
        block += line
        if line.strip() == "End": break
    else:
        if line.strip() == "Start":
            found = True
            block = "Start"

data_file.close()
Run Code Online (Sandbox Code Playgroud)

  • @BPm:这是一个"有限状态机"的例子(http://en.wikipedia.org/wiki/Finite_state_machine):机器以"Block not yet found"状态启动(找到== False),保持在"块内"(找到== True)状态下运行,在这种情况下,当找到"结束"时停止.它们可能效率低一些(这里,必须为块中的每一行检查`found`),但是状态机通常允许人们干净地表达更复杂算法的逻辑. (4认同)