Computer >> Computer tutorials >  >> Programming >> Python

How to 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)