从二进制文件读取字符串 [英] Read string from binary file
问题描述
我想从文件中读取字节1,2和3.我知道它对应一个字符串(在这种情况下,它是Linux二进制标头的ELF
)
I want to read bytes 1,2 and 3 from a file. I know it corresponds to a string (in this case it's ELF
of a Linux binary header)
以下是我在网上可以找到的示例:
Following examples I could find on the net I came up with this:
with open('hello', 'rb') as f:
f.seek(1)
bytes = f.read(3)
string = struct.unpack('s', bytes)
print st
查看 struct 的官方文档,似乎通过了s
作为参数应该允许我读取字符串.
Looking at the official documentation of struct it seems that passing s
as argument should allow me to read a string.
我得到了错误:
st = struct.unpack('s', bytes)
struct.error: unpack requires a string argument of length 1
使用Python 2.7
Using Python 2.7
推荐答案
在您的特殊情况下,只需进行检查即可
In your special case, it is enough to just check
if bytes == 'ELF':
一步测试所有三个字节为三个字符E
,L
和F
.
to test all three bytes in one step to be the three characters E
, L
and F
.
但是,如果您要检查数值,则无需在此处解包任何内容.只需使用ord(bytes[i])
(i分别为0、1、2)来获取三个字节的字节值即可.
But also if you want to check the numerical values, you do not need to unpack anything here. Just use ord(bytes[i])
(with i in 0, 1, 2) to get the byte values of the three bytes.
或者您可以使用
byte_values = struct.unpack('bbb', bytes)
获得三个字节的元组.如果字节具有如下可命名的语义,您也可以即时解开该元组:
to get a tuple of the three bytes. You can also unpack that tuple on the fly in case the bytes have nameable semantics like this:
width, height, depth = struct.unpack('bbb', bytes)
使用'BBB'
代替'bbb'
,以防您的字节值无符号.
Use 'BBB'
instead of 'bbb'
in case your byte values shall be unsigned.
这篇关于从二进制文件读取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!