1

如何在 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()
4

2 回答 2

6

最简单(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 中使用导入形式的未来)比旧的 try/finally 在清晰和简洁方面更好。

于 2010-05-19T14:00:13.697 回答
0

改变

idList = struct.unpack("=l", bytes_read)

idList.append(struct.unpack("=l", bytes_read)[0])
于 2010-05-19T14:32:22.647 回答