简体   繁体   中英

How to write int array [0,1,2,…] in binary to a file using Python script

I'm new to Python. I want to generate a 100K binary file. The file contents will be (in hex):

00000000 00000001 00000002 00000003
00000004 00000005 00000006 00000007
...

I read some examples, but they all write a string to a text file. That's not what I want.

First, you can use the struct module to pack each number into a four-byte binary string. (See: Convert a Python int into a big-endian string of bytes )

Then, just loop from 0-25,000 and write each number to your file. Since each number is four bytes, this will produce a 100K file. For example:

import struct

f = open("filename","wb")
for i in range(25000):
    f.write(struct.pack('>I', i))
f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM