Creating random binary files

IMHO – the following is completely redundant:

f.write(struct.pack("=I",random.randint(0,sys.maxint*2+1)))

There’s absolutely no need to use struct.pack, just do something like:

import os

fileSizeInBytes = 1024
with open('output_filename', 'wb') as fout:
    fout.write(os.urandom(fileSizeInBytes)) # replace 1024 with a size in kilobytes if it is not unreasonably large

Then, if you need to re-use the file for reading integers, then struct.unpack then.

(my use case is generating a file for a unit test so I just need a
file that isn’t identical with other generated files).

Another option is to just write a UUID4 to the file, but since I don’t know the exact use case, I’m not sure that’s viable.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)