ice-wind
ice-wind

Reputation: 868

How to create a file with a set size in python?

The file format I'm handling has a header of 8192 bytes at the front of the file. In order to create an empty file, I need a zeroed out header (file format spec is out of my control). My current solution is this :

with open(fileName, mode='w+b') as f:
    for i in range(8192):
        f.write(b'\x00')

Is there a better (more efficient) way to do this ?

Upvotes: 3

Views: 1393

Answers (3)

wim
wim

Reputation: 362517

Truncate is much more efficient than writing out null bytes:

with open(fileName, mode='wb') as f:
    f.truncate(8192)

Upvotes: 1

Daweo
Daweo

Reputation: 36370

You might multiply python bytes by integers similarly to strs, so for example x = b'\x00' * 3 is equivalent to x = b'\x00\x00\x00' therfore instead of:

with open(fileName, mode='w+b') as f:
    for i in range(8192):
        f.write(b'\x00')

you might do:

with open(fileName, mode='w+b') as f:
    f.write(b'\x00' * 8192)

which write once.

Upvotes: 0

tzaman
tzaman

Reputation: 47770

Use the bytes builtin:

with open(filename, 'wb') as f:
    f.write(bytes(8192))

From the docs:

The optional source parameter can be used to initialize the array in a few different ways:

  • If it is an integer, the array will have that size and will be initialized with null bytes.

Upvotes: 3

Related Questions