Binary Files
Reading and writing binary files is pretty straight forward.
from struct import pack, unpack
bin_filepath=r"c:\temp\my_bin_file.bin"
with open(bin_filepath, "wb") as bin_file:
bin_file.write( pack('f', 31.323 ))
bin_file.write( pack('I', 8462 ))
# fill with zeroes
count=245
bin_file.write(pack('I'*count, *[0 for x in range(count)] ))
# write a tuple
my_val = (0.3, 3.2, 1.66, 9.431)
bin_file.write( pack('ffff', *my_val ) )
with open(bin_filepath, "rb") as bin_file:
# read a float value
# struct.unpack always tuple, even if only 1 value!
float_value = unpack('f', bin_file.read(4))[0]
# read an unsigned int
int_value = unpack('I', bin_file.read(4))[0]
# jump to position 245
bin_file.seek(245)
# read a 2-value tuble
vector2_value = unpack('ff', bin_file.read(8))
# read a 4-value tuple
vector4_value = unpack('ffff', bin_file.read(16))
The format string consists of these:
| Format | C Type | Python type | Standard size |
|---|---|---|---|
x |
pad byte | no value | |
c |
char | bytes of length 1 | 1 |
b |
signed char | integer | 1 |
B |
unsigned char | integer | 1 |
? |
_Bool | bool | 1 |
h |
short | integer | 2 |
H |
unsigned short | integer | 2 |
i |
int | integer | 4 |
I |
unsigned int | integer | 4 |
l |
long | integer | 4 |
L |
unsigned long | integer | 4 |
q |
long long | integer | 8 |
Q |
unsigned long long | integer | 8 |
n |
ssize_t | integer | |
N |
size_t | integer | |
e |
(6) | float | 2 |
f |
float | float | 4 |
d |
double | float | 8 |
s |
char[] | bytes | |
p |
char[] | bytes | |
P |
void* | integer |
You can jump to file positions with seek