Create File of Particular Size in Python



To create a file of a particular size, just seek to the byte number(size) you want to create the file of and write a byte there.

For example

with open('my_file', 'wb') as f:
    f.seek(1024 * 1024 * 1024) # One GB
    f.write('0')

This creates a sparse file by not actually taking up all that space. To create a full file, you should write the whole file:

with open('my_file', 'wb') as f:
    num_chars = 1024 * 1024 * 1024
    f.write('0' * num_chars)
Updated on: 2019-12-12T08:04:51+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements