【问题标题】:What is the most efficient way to read a large binary file python读取大型二进制文件python的最有效方法是什么
【发布时间】:2014-11-03 11:27:57
【问题描述】:

我有一个大 (21 GB) 文件,我想将其读入内存,然后传递给一个子程序,该子程序对我透明地处理数据。我在 Centos 6.5 上使用 python 2.6.6,因此升级操作系统或 python 不是一个选项。目前,我正在使用

f = open(image_filename, "rb")
image_file_contents=f.read()
f.close()
transparent_subroutine ( image_file_contents )

这很慢(约 15 分钟)。在开始阅读文件之前,我知道文件有多大,因为我调用 os.stat(image_filename).st_size

所以如果有意义的话,我可以预先分配一些内存。

谢谢

【问题讨论】:

  • 更大的缓冲区可能会有所帮助open(image_filename, 'rb', 64*1024*1024)
  • 您打算如何访问数据?随机访问?阅读一个块,处理,重复?还是您实际上需要将整个文件映射到内存中?
  • 我不知道如何访问数据。它是 openstack 程序 Glance 的输入,它使用它来创建一个卷。我没有尝试更改缓冲区大小,这很聪明。

标签: python file binary memory-efficient


【解决方案1】:

按照 Dietrich 的建议,我测量这种 mmap 技术比 1.7GB 输入文件的一次大读取快 20%

from zlib import adler32 as compute_cc

n_chunk = 1024**2
crc = 0
with open( fn ) as f:
  mm = mmap.mmap( f.fileno(), 0, prot = mmap.PROT_READ, flags = mmap.MAP_PRIVATE )
  while True:
    buf = mm.read( n_chunk )
    if not buf: break
    crc = compute_crc( buf, crc )
return crc

【讨论】:

    【解决方案2】:

    使用生成器

    def generator(file_location):
    
        with open(file_location, 'rb') as entry:
    
            for chunk in iter(lambda: entry.read(1024 * 8), b''):
    
                yield chunk
    
    
    go_to_streaming = generator(file_location) 
    

    【讨论】:

      猜你喜欢
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2010-11-20
      • 2017-04-15
      • 2019-10-02
      • 2014-02-01
      相关资源
      最近更新 更多