代码之家  ›  专栏  ›  技术社区  ›  Cerin

如何在Python中读取大文件的特定部分

  •  20
  • Cerin  · 技术社区  · 13 年前

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

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

    open(filename).read()[start_index:end_index]
    
    2 回复  |  直到 13 年前
        1
  •  35
  •   Dan Lecocq    13 年前

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

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

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

        2
  •  1
  •   Will Leeney    6 年前

    这是我的可变宽度编码解决方案。我的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