将Python中的二进制文件读入stru

2024-09-24 20:37:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件readbytes数据文件二进制openfilename结构
2条回答

改变

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

idList.append(struct.unpack("=l", bytes_read)[0])

最简单(Python2.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模块处理得最好的任务(例如,由于bet的原因)

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在清晰度和简洁性方面更好。

相关问题 更多 >