How to create a bin file using Python?
One common way to generate a binary file in Python is to use the open() function to open the file and the write() method to write data to the file. Here is a simple example code demonstrating how to generate a bin file containing binary data:
data = b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21' # 二进制数据
with open('example.bin', 'wb') as f:
f.write(data)
print("bin文件已生成")
In the above example, a binary data named “data” is first defined. Then, a file named “example.bin” is opened using open(‘example.bin’, ‘wb’) in binary write mode (‘wb’). Next, the binary data is written into the file using f.write(data). Finally, the file is closed and a message is output.
After running the code, a binary file named example.bin will be generated, which contains binary data.