Skip to main content
 首页 » 编程设计

Python 读取二进制 : how to unpack a large number of numbers

2025年05月04日10TianFang

基本上我想读取一个包含大量 double 的二进制文件。不确定如何实现以下目标:

N=10000000 
fin=open("sth.bin","rb") 
data = struct.unpack('dddddd......',fin.read(8*N)) #of course not working, but this is what I want 
fin.close() 

请您参考如下方法:

遍历文件,一次解压 block :

with open("sth.bin", "rb") as f: 
    numbers = [ 
        struct.unpack('d', chunk)[0] 
        for chunk in iter(lambda: f.read(8), "") 
    ] 

你可以在这里做很多优化——一次读取更大的文件 block (4096 字节通常是理想的)并创建一个 compiled Struct ——但这是一般的想法。如果性能特别重要,您还可以一次解压多个 double (例如,struct.unpack('d' * 8, chunk))以减少函数调用次数:

numbers = [] 
struct_4096 = struct.Struct("d" * 4096 / 8) 
with open("sth.bin", "rb") as f: 
    while True: 
        chunk = f.read(4096) 
        try: 
            numbers.extend(struct_4096.unpack(chunk)) 
        except struct.error: 
            numbers.extend(struct.unpack("d" * len(chunk) / 8))