1

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.

1
  • Do you want literal zeros, commas, and x's in your file? If so, should there be spaces after the commas? Commented Mar 28, 2014 at 4:16

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

3 Comments

if all of his values will fit in 8 bits, he could just use chr, correct?
@Broseph He could just use chr if he wanted 8-bit numbers, but he wanted 32-bit binary numbers in the file.
Oh yes, my mistake. It is still possible to do this without struct, but that would be pointless. Unless this is homework and the teacher wants them to play with bits, lol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.