我想从文件中读取1、2和3字节的数据。 我知道它对应于Linux二进制文件头中的字符串(在这种情况下是ELF
)。
根据我在网上找到的示例,我得出了以下代码:
with open('hello', 'rb') as f:
f.seek(1)
bytes = f.read(3)
string = struct.unpack('s', bytes)
print st
查看struct的官方文档,似乎将s
作为参数传递可以让我读取一个字符串。
但我遇到了错误:
st = struct.unpack('s', bytes)
struct.error: unpack requires a string argument of length 1
编辑:使用Python 2.7版本
f.read()
在Python 2和3中都返回bytes
。在文本模式下打开时,open
使用locale.getpreferredencoding(False)
编码,这在Python 3中有时可能是utf-8。 - jfs