小编Vip*_*pin的帖子

在python中读取二进制文件

我写了一个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()
Run Code Online (Sandbox Code Playgroud)

它工作得很好,然后我尝试使用下面的代码读取'test.bin'文件.

import struct  
inh = open('test.bin', 'rb')  
for rec in inh:  
    pos = struct.unpack('i', rec)  
    print pos  
inh.close()
Run Code Online (Sandbox Code Playgroud)

但它失败并显示错误消息:

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
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用这些文件阅读struct.unpack.
非常感谢,Vipin

python

2
推荐指数
2
解决办法
1万
查看次数

标签 统计

python ×1