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

时间:2013-03-26 18:36:57

标签: python parsing

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

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

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

2 个答案:

答案 0 :(得分:21)

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

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

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

答案 1 :(得分:0)

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