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.

Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
user1932637
  • 183
  • 2
  • 12

1 Answers1

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()
Community
  • 1
  • 1
Carter Sande
  • 1,789
  • 13
  • 26
  • if all of his values will fit in 8 bits, he could just use `chr`, correct? – Broseph Mar 28 '14 at 04:22
  • @Broseph He could just use `chr` if he wanted 8-bit numbers, but he wanted 32-bit binary numbers in the file. – Carter Sande Mar 28 '14 at 04:24
  • 1
    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. – Broseph Mar 28 '14 at 04:26