python-从文件的特定行中读取文件

发布于 2021-01-29 19:32:06

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

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

我希望你知道我的意思。我正在考虑遍历文件,然后使用正则表达式搜索以找到“开始”和“结束”的行号,然后使用线缓存从开始行读取到结束行。但是如何获得行号?我可以使用什么功能?

关注者
0
被浏览
148
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果您只想要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.)
    

    实际上,您不需要操纵行号即可读取开始和结束标记之间的数据。

    在两个块中都重复了逻辑(“读到…”),但是它非常清楚和有效(其他方法通常涉及[在块之前/块内/块结束之前]检查某些状态,这会产生时间损失)。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看