[BioPython] byte packing and binary files

Andrew Dalke dalke@acm.org
Mon, 8 Jan 2001 12:09:24 -0700


Scott Kelley:
>I know you can use the struct library to pack numbers as doubles:
> pack('d',
>number) but can you then write these to a binary file easily? Is there
>another way to do this that I don't know about?
>
>The file I want to write is just a list of number (two ints and a float)
>that looks like this:
>
>2    5    8.9035
>2    7    10.988


 ==== spam.py
import struct

data = (
  (1, 2, 5.1),
  (2, 3, 5.2),
  (3, 4, 5.3),
  (2, 5, 5.4),
  (-1, -2, -3.5),
  )

outfile = open("tmp.dat", "wb")
for i1, i2, f1 in data:
    outfile.write(struct.pack("iif", i1, i2, f1))
outfile.close()

  ==== spam.c

#include <stdio.h>
main() {
  FILE *infile;
  typedef struct {
    int num1;
    int num2;
    float float1;
  } kelley;
  kelley data[5];
  int i, count;

  infile = fopen("tmp.dat", "rb");
  if (!infile) {
    printf("Cannot open\n");
    exit(-1);
  }

  count = fread(data, sizeof(kelley), 5, infile);
  if (count != 5) {
    printf("Cannot read 5 elements; got %d\n", count);
    exit(-1);
  }
  for (i=0; i<5; i++) {
    printf("%d num1 %d num2 %d float1 %f\n", i, data[i].num1,
           data[i].num2, data[i].float1);
  }
}

 ==== Testing it

$ python spam.py
$ cc spam.c
$ ./a.out
0 num1 1 num2 2 float1 5.100000
1 num1 2 num2 3 float1 5.200000
2 num1 3 num2 4 float1 5.300000
3 num1 2 num2 5 float1 5.400000
4 num1 -1 num2 -2 float1 -3.500000
$


                    Andrew
                    dalke@acm.org