Binary file read and write

Original link:current page

Description:

No usage information.


Read/Write/Append

No matter read or write, different from the normal mode, it beed a “b” to specify it's a bianry file.

  import struct from pack
  # read
  binary_file = open(binary_file_name, 'rb')
  data = binary_file.read();
  print(data)
  binary_file.close()
 
  # write
  binary_file = open(path, 'wb')
  data = binary_file.write(pack);
  # data_type is a list of int, write data as unsigned short, for more type please see link(1) below
  flash_file_src.write(pack("<"+len(data_byte)*"h"(), *data_byte))
  binary_file.close()
 
  # append
  binary_file = open(path, 'ab+')
  data = binary_file.write(pack);
  # data_type is a list of int, write data as unsigned short
  flash_file_src.write(pack("<"+len(data_byte)*"h", *data_byte))
  binary_file.close()

more information see use struct.pack to write int data to file

Check

After you finished the binary file edit, you may need to check whether the result is what you expect or not.
Tools as follow would be helpful:

  • notepad++ with Hex Edit plugin
  • Ultra Edit
  • od command in Linux

For od command, here is command:

show data in hex format

$ od -h binary_file_name

show data in oct format

$ od -o binary_file_name

  • Last modified: 2019/10/14 14:37