Creating random binary files

后端 未结 2 1961
情歌与酒
情歌与酒 2021-02-04 03:21

I\'m trying to use python to create a random binary file. This is what I\'ve got already:

f = open(filename,\'wb\')
for i in xrange(size_kb):
    for ii in xrang         


        
2条回答
  •  粉色の甜心
    2021-02-04 03:41

    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
    
    with open('output_file', 'wb') as fout:
        fout.write(os.urandom(1024)) # replace 1024 with size_kb if 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.

提交回复
热议问题