How Does One Read Bytes from File in Python

家住魔仙堡 提交于 2019-12-04 03:47:49

If you have a string, with 2 bytes that you wish to interpret as a 16 bit integer, you can do so by:

>>> s = '\0\x02'
>>> struct.unpack('>H', s)
(2,)

Note that the > is for big-endian (the largest part of the integer comes first). This is the format id3 tags use.

For other sizes of integer, you use different format codes. eg. "i" for a signed 32 bit integer. See help(struct) for details.

You can also unpack several elements at once. eg for 2 unsigned shorts, followed by a signed 32 bit value:

>>> a,b,c = struct.unpack('>HHi', some_string)

Going by your code, you are looking for (in order):

  • a 3 char string
  • 2 single byte values (major and minor version)
  • a 1 byte flags variable
  • a 32 bit length quantity

The format string for this would be:

ident, major, minor, flags, len = struct.unpack('>3sBBBI', ten_byte_string)
Owen

Why write your own? (Assuming you haven't checked out these other options.) There's a couple options out there for reading in ID3 tag info from MP3s in Python. Check out my answer over at this question.

I am trying to read in an ID3v2 tag header

FWIW, there's already a module for this.

I was going to recommend the struct package but then you said you had tried it. Try this:

self.major_version = struct.unpack('H', self.whole_string[3:5])

The pack() function convers Python data types to bits, and the unpack() function converts bits to Python data types.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!