How to create file of particular size in Python?

Creating a file of a specific size in Python can be accomplished using two main approaches: creating a sparse file (which doesn't actually allocate disk space) or creating a full file (which allocates the entire specified size on disk).

Creating a Sparse File

A sparse file appears to have the desired size but doesn't actually consume disk space until data is written. Use seek() to move to the target position and write a single byte ?

# Create a 1GB sparse file
with open('sparse_file.txt', 'wb') as f:
    f.seek(1024 * 1024 * 1024)  # Move to 1GB position
    f.write(b'0')  # Write one byte

print("Sparse file created successfully")
Sparse file created successfully

Creating a Full File

To create a file that actually occupies the specified disk space, write the entire content to fill the file ?

# Create a 1MB full file (using smaller size for demo)
file_size = 1024 * 1024  # 1MB
with open('full_file.txt', 'wb') as f:
    f.write(b'0' * file_size)

print("Full file created successfully")
Full file created successfully

Using os.truncate() Method

Another approach is using os.truncate() to set the file size directly ?

import os

# Create file and set size using truncate
with open('truncated_file.txt', 'wb') as f:
    f.truncate(1024 * 1024)  # Set to 1MB

print("File created using truncate method")
File created using truncate method

Comparison of Methods

Method Disk Space Used Performance Best For
Sparse File (seek + write) Minimal Very Fast Placeholder files
Full File (write all bytes) Complete Slower for large files Files that need actual space
truncate() method Varies by OS Fast Setting file size precisely

Conclusion

Use sparse files with seek() and single byte write for quick placeholder files. Use full file creation by writing all bytes when you need guaranteed disk space allocation.

Updated on: 2026-03-24T17:23:18+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements