Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I efficiently fill a file with null data from python?

Tags:

python

file

I need to create files of arbitrary size that contain no data. The are potentially quite large. While I could just loop through and write a single null character until I've reached the file size, that seems ugly.

with open(filename,'wb') as f:
   # what goes here?

What is the efficient, pythonic way to do this?

like image 808
Daniel Von Fange Avatar asked Jul 31 '10 11:07

Daniel Von Fange


2 Answers

You can seek to a specific position and write a byte, and the OS will magically make the rest of the file appear.

with open(filename, "wb") as f:
    f.seek(999999)
    f.write("\0")

You need to write at least one byte for this to work.

like image 183
Greg Hewgill Avatar answered Oct 05 '22 11:10

Greg Hewgill


with open('zero', 'w') as f:
    f.seek(999999999)
    f.write('\0')

Will create a sparse file if the OS supports it. The magic is that files created this way do not take any space (until you copy it elsewhere with a program that does not preserve holes)

like image 35
Marco Mariani Avatar answered Oct 05 '22 12:10

Marco Mariani