How to create a small binary file in Python.
python
import struct
def main():
with open("data", "wb") as fout:
for x in [0xFF, 0x12, 0x89]:
fout.write(struct.pack("B", x))
if __name__ == "__main__":
main()
Let's check the contents of the file created by the hexdump
command.
% hexdump data
0000000 ff 12 89
0000003
You can make it without any problems.
(Addition 2013-09-07)
shiracamus told me about bytearray in the comments. This is easier because you don't need to import.
python
def main():
with open("data", "wb") as fout:
bary = bytearray([0xFF, 0x12, 0x89])
bary.append(0)
bary.extend([1, 127])
fout.write(bary)
if __name__ == "__main__":
main()
This is the execution result of hexdump
.
% hexdump data
0000000 ff 12 89 00 01 7f
0000006
Recommended Posts