Python Write Binary File

Continue with my last posting about python read binary file, Now I want to create a posting about how python write binary file. Write binary file in python is like reading file. But, we must modifed about ‘r’ parameter with ‘w’ parameter. This is a sample code how python write binary file code :

# -*- coding: utf-8 -*-
str = "abcdefgh"
fod = open("writebinary.bin", "wb")
fod.write(str)
fod.close()

This python write binary file code will write text in variable str to file with name writebinary.bin.

Example above is a method to write character in binary file. When we use C/C++, we can save other datatype (ex. int, float, double, etc) to binary file. When we save 1 integer data type with binary mode, we can get 4 byte in output file. Because integer size is equal with 4 byte. In the next example, I want to save integer data type to binary file with python. Please check this python write binary file with integer data type :

# -*- coding: utf-8 -*-import struct
istr = [100, 200, 300]
fod = open("writebinary.bin", "wb")
for i in range(3):  
   itext = struct.pack("i", istr[i])  
   fod.write(itext)
fod.close()

From this code, we will save data in variable array of integer istr to binary file. Output from this code is a file writebinary.bin with size 12 byte (4 byte integer * 3 data). struct.pack is a method to decompose a value to array of value we defined. From above example, we change value from item in array (integer data type) become 4 byte character. If you want to check output from this program with C, you can use this code (in C, save as readbinary.c) :

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv)
{  
  FILE *fid;  int *a;

  fid = fopen("writebinary.bin","r");  
  a = (int*) calloc(3, sizeof(int));  
  fread(a, sizeof(int), 3, fid);  
  int i;  for(i=0; i<3; i++)    
    printf("%i \n", a[i]);  
  fclose(fid);
  return(1)
}

Compile this code with command gcc readbinary.c -o readbinary. This is output from this program :

toto@toto-laptop:~/Documents$ ./readbinay
100
200
300

With this example, you can write your data with Python in other data format (like float or double). This is my simple method how python write binary file and how to check output from python write binary file with C. If you have any question about python write binary file, please send me a question :)

totosugito

Hi, This is my notes when I try something. Maybe, this is NOT THE BEST SOLUTION for your problems. If you have other method or idea that better with my post, please share in this blog. Thank for visiting my site.

More Posts - Website

Leave a Reply