What could be the simplest Python equivalent to the following C code?
#include <stdio.h>
int main(void) {
struct dog {
char breed[16];
char name[16];
};
struct person {
char name[16];
int age;
struct dog pets[2];
};
struct person p = {
"John Doe", 20, {{"Lab", "Foo"}, {"Pug", "Bar"}}
};
FILE *fp = fopen("data_from_c.txt", "w");
fwrite(&p, sizeof(p), 1, fp);
fclose(fp);
return 0;
}
My main goal here is to write the data to the file as contiguous bytes:
$ xxd data_from_c.txt
00000000: 4a6f 686e 2044 6f65 0000 0000 0000 0000 John Doe........
00000010: 1400 0000 4c61 6200 0000 0000 0000 0000 ....Lab.........
00000020: 0000 0000 466f 6f00 0000 0000 0000 0000 ....Foo.........
00000030: 0000 0000 5075 6700 0000 0000 0000 0000 ....Pug.........
00000040: 0000 0000 4261 7200 0000 0000 0000 0000 ....Bar.........
00000050: 0000 0000 ....
So far, I have tried using namedtuple
s and the struct
module for packing the Python values:
from collections import namedtuple
import struct
dog = namedtuple('dog', 'breed name')
person = namedtuple('person', 'name age pets')
p = person(
name=b'John Doe',
age=22,
pets=(dog(breed=b'Lab', name=b'Foo'), dog(breed=b'Pug', name=b'Bar'))
)
with open('data_from_python.txt', 'wb') as f:
b = struct.pack('<16s i 16s 16s 16s 16s', *p)
f.write(b)
However, the *p
unpacking does not unpack the iterable recursively. Is there a way for doing this properly?
If there is an alternative to doing this that doesn't involve using struct
or namedtuple
, that would be welcome too.