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
Looking at the official documentation of struct it seems that passing s as argument should allow me to read a string.
I get the error:
st = struct.unpack('s', bytes)
struct.error: unpack requires a string argument of length 1
EDIT: Using Python 2.7
f.read()returnsbyteson both Python 2 and 3 if the file is opened in a binary mode'b'(OP uses 'rb' i.e., binary).openin text mode useslocale.getpreferredencoding(False)encoding that sometimes may be utf-8 in Python 3bytesname. It shadows the builtin function.