【发布时间】:2014-06-18 21:34:52
【问题描述】:
我想从文件中读取字节 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
【问题讨论】:
-
请指定您使用的 Python 版本。在 Python 2 中,“str”和“bytes”是别名。在 Python 3 中,file.read() 尝试使用 UTF-8 编码将字节转换为 unicode。
-
@Grapsus:这是错误的。
f.read()在 Python 2 和 3 上返回bytes如果文件以二进制模式打开'b'(OP 使用 'rb' 即二进制)。 text 模式下的open使用locale.getpreferredencoding(False)编码,有时 在 Python 3 中可能是 utf-8 -
不要使用
bytes名称。它隐藏了内置函数。
标签: python string python-2.7 binary