我编写了一个Python脚本来创建整数的二进制文件。
import struct
pos = [7623, 3015, 3231, 3829]
inh = open('test.bin', 'wb')
for e in pos:
inh.write(struct.pack('i', e))
inh.close()
它之前运作良好,然后我尝试使用以下代码读取'test.bin'文件。
import struct
inh = open('test.bin', 'rb')
for rec in inh:
pos = struct.unpack('i', rec)
print pos
inh.close()
但是它失败了,并显示出一个错误信息:
Traceback (most recent call last):
File "readbinary.py", line 10, in <module>
pos = struct.unpack('i', rec)
File "/usr/lib/python2.5/struct.py", line 87, in unpack
return o.unpack(s)
struct.error: unpack requires a string argument of length 4
我想知道如何使用struct.unpack
读取这些文件。
非常感谢,Vipin
import functools; reader= functools.partial(f.read, 4); for rec in iter(reader, ''):
结构。否则,可以避免使用functools及其加速:for rec in iter(lambda: f.read(4), '')
- tzot