[英]What is the most efficient way to read a large CSV file ( 10 M+ records) located on S3 (AWS) with Python?
[英]What is the most efficient way to read a large binary file python
我有一个大(21 GByte)文件,我想将其读入内存,然后传递给一个子程序,该子程序对我透明地处理数据。 我在 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
所以如果有意义的话,我可以预先分配一些内存。
谢谢
按照迪特里希的建议,我测量了这种 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
使用发电机
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.