LoginSignup
1
0

More than 3 years have passed since last update.

Writing and reading a binary file with python

Last updated at Posted at 2019-05-20

1. Requirements

Ubuntu16.04
Python3.x

2. Refference

https://docs.python.org/ja/3/library/struct.html

3. Sample codes (main.py)

function
import struct                                                                                                    

'''
  Charactor, Byte-order
  @,         native
  <,         little endian
  >,         big endian

  Format, C-type,         Python-type, Size[byte]
  c,      char,           byte,        1
  b,      signed char,    integer,     1
  B,      unsigned char,  integer,     1
  h,      short,          integer,     2
  H,      unsigned short, integer,     2
  i,      int,            integer,     4
  I,      unsigned int,   integer,     4
  f,      float,          float,       4
  d,      double,         float,       8
'''

def bwrite(data, filename):
  with open(filename, "wb") as f:
    for x in data:
      f.write(struct.pack('b', x)) # 1byte

def bread(filename):
  with open(filename, 'rb') as f:
    bdata = []
    while True:
      bytes = f.read(1)
      if bytes == b'':
        break
      else:
        bdata.append(struct.unpack('b', bytes)[0]) # 1byte
  hdata = [hex(x) for x in bdata]
  return bdata, hdata

def main():
  bwrite([0x00, 0x11, 0x22, 0x33], 'binary.dat')
  bdata, hdata = bread('binary.dat')
  print('bdata', bdata)
  print('hdata', hdata)

if __name__ == "__main__":
  main()

4. Results

$ python main.py 
bdata [0, 17, 34, 51]
hdata ['0x0', '0x11', '0x22', '0x33']

$ hexdump binary.dat 
0000000 1100 3322                              
0000004

Thank you.
last-samurai

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0