Python - Writing a specific amount of bytes in a Binary file

1.3k Views Asked by At

Sorry if this is a duplicate question, I'm fairly new to python and don't fully know the nomenclature so its hard to search for solutions.

I'm trying to write a code that outputs a binary file in specific integer formats, ie a section in 8 bit, followed by 32 bit, etc. More specifically, in STL format; an outline can be read here: wikipedia.

I have tried doing a simple f.write(struct.pack(DATA)) to produce an output file, however the end result is a corrupted file. STL does have an ASCII version; which I have working. Therefore I assume something is wrong with the binary file generation. I want to use Binary to reduce the file size significantly.

I assume the output code would look something like this*:

import struct
    f = open('cool_filename.stl', 'wb')
    f.write(struct.pack(head, format=UINT8))
    f.write(struct.pack(num, format=UINT32))
    for i in range(0, num):
        f.write(struct.pack(normal, format=REAL32))
        f.write(struct.pack(vert1, format=REAL32))
        f.write(struct.pack(vert2, format=REAL32))
        f.write(struct.pack(vert3, format=REAL32))
        f.write(struct.pack(attr, format=UINT16))
    f.close()

Useful links:

struct.pack docs

format specs

I believe the answer can be found in the latter link above, but I don't really understand how to use it. Following it, I've tried using struct.pack(I32, DATA) to format for the unsigned 32 byte sections, and similar code for the rest, but it doesn't work.

*I should note that this doesn't run. The code here to show the format changes

1

There are 1 best solutions below

4
On

The first argument to struct.pack should be a string, and the I format spec implies 32 bits (size=4 in the table in the docs means 4 bytes, i.e 4*8=32 bits), so to write a single 32-bit unsigned integer (say, 4711) in little-endian byte order, you would do struct.pack('<I', 4711).