Skip to main content
 首页 » 编程设计

python之将 Python 中的二进制文件读入结构

2025年05月04日19zhengyun_ustc

如何在 Python 中打开二进制数据文件并读回一个 long 的值 一次,进入一个结构。我现在有这样的东西,但我认为这会继续覆盖 idList,我想附加到它,所以我最终得到了所有 long 值的元组在文件中-

file = open(filename, "rb") 
    try: 
        bytes_read = file.read(struct.calcsize("=l")) 
        while bytes_read: 
            # Read 4 bytes(long integer) 
            idList = struct.unpack("=l", bytes_read) 
            bytes_read = file.read(struct.calcsize("=l")) 
    finally: 
        file.close() 

请您参考如下方法:

最简单的(python 2.6 或更高版本):

import array 
idlist = array.array('l') 
with open(filename, "rb") as f: 
    while True: 
        try: idlist.fromfile(f, 2000) 
        except EOFError: break 
idtuple = tuple(idlist) 

元组是不可变的,所以它们不能增量构建:所以你必须构建一个不同的(可变的)序列,然后在最后调用它的 tuple 。如果您实际上不需要特别是一个元组,当然,您可以省去最后的、昂贵的步骤并保留数组或列表或其他任何东西。无论如何,避免践踏像 file 这样的内置名称是可取的;-)。

如果您必须使用struct 模块来处理最好由array 模块处理的工作(例如,因为打赌) ,

idlist = [ ] 
with open(filename, "rb") as f: 
    while True: 
        bytes_read = f.read(struct.calcsize("=l")) 
        if not bytes_read: break 
        oneid = struct.unpack("=l", bytes_read)[0] 
        idlist.append(oneid) 

with 语句(也可在 2.5 中使用, future 可以导入)在清晰度和简洁性方面优于旧的 try/finally。