Pandrei Pandrei - 5 months ago 7x
Python Question

how can you overwrite a file line with zeros

I am trying to find the best way to overwrite a file with zeros; every character in the file will be replaced by 0.

currently I have this working:

import fileinput
for line in fileinput.FileInput('/path/to/file', inplace =1):
for x in line:
x = 0

But this looks very inefficient; is there a better way to do it?


Instead of replacing the characters one by one, I prefer to create a new file with the same name and same size:

Obtaining size of current file:

>>> file_info = os.stat("/path/to/file")
>>> size = file_info.st_size

Creating another file containing 0x00 with the same size:

>>> f = open("/path/to/file", "w")
>>>  - 1)
>>> f.write("\x00")
>>> f.close()

I assumed by 0, you meant 0x00 byte value