【问题标题】:How to read specific part of large file in Python如何在 Python 中读取大文件的特定部分
【发布时间】:2019-06-29 21:05:32
【问题描述】:

给定一个大文件(数百 MB),我将如何使用 Python 快速读取文件中特定开始和结束索引之间的内容?

本质上,我正在寻找一种更有效的方法:

open(filename).read()[start_index:end_index]

【问题讨论】:

    标签: python parsing


    【解决方案1】:

    您可以将seek 放入文件中,然后从那里读取一定数量的文件。 Seek 允许您获取文件中的特定偏移量,然后您可以将读取限制为仅该范围内的字节数。

    with open(filename) as fin:
        fin.seek(start_index)
        data = fin.read(end_index - start_index)
    

    这只会读取您正在寻找的数据。

    【讨论】:

    • 请注意,这仅与 OP 的单字节编码文件(如 ASCII)或二进制文件的代码等效,因为 OP 的 start_indexend_index 是字符位置,而 seek()read() 适用于字节位置。当您有可变宽度编码的文件时,您可能必须对文件进行解码才能正确索引。
    • 这是一个非常好的观点。我非常喜欢 ASCII 模式 :-)
    • 还有一点:如果你试图读取一个文件的多个连续段,fin.read(n) 会自动将读取指针设置为下一个要读取的字节。
    【解决方案2】:

    这是我的可变宽度编码解决方案。我的 CSV 文件包含一个字典,其中每一行都是一个新项目。

    def get_stuff(filename, count, start_index):
        with open(filename, 'r') as infile:
                 reader = csv.reader(infile)
                 num = 0 
                 for idx, row in enumerate(reader):
                     if idx >= start_index-1:
                         if num >= count:
                             return
                     else:
                         yield row 
                         num += 1
    

    【讨论】:

    • 您好@Will,从第 2 行开始,您的所有代码都存在缩进问题
    • @BertrandGazanion 对此感到抱歉,现在应该修复
    猜你喜欢
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    相关资源
    最近更新 更多