如何在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()
改变
到
最简单(Python2.6或更高版本):
元组是不可变的,因此它们不能以增量方式构建:因此您必须构建一个不同的(可变的)序列,然后在它的末尾调用
tuple
。当然,如果您实际上不需要一个元组,那么您可以保存最后一个代价高昂的步骤,并保留数组或列表等。无论如何,最好避免践踏内置名称,如file
;-)。如果让使用
struct
模块来完成由array
模块处理得最好的任务(例如,由于bet的原因)with
语句(在2.5中还提供了一个将来的导入表单)比旧的try/finally在清晰度和简洁性方面更好。相关问题 更多 >
编程相关推荐