Pandrei
Pandrei

Reputation: 4951

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?

Upvotes: 0

Views: 341

Answers (4)

EbraHim
EbraHim

Reputation: 2349

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")
>>> f.seek(size  - 1)
>>> f.write("\x00")
>>> f.close()
>>> 

I assumed by 0, you meant 0x00 byte value

Upvotes: 1

Ian2thedv
Ian2thedv

Reputation: 2701

Using a regex is probably cleaner, but here is a solution using fileinput:

import fileinput
import sys
for line in fileinput.FileInput('/path/to/file', inplace=True):
    line = '0' * len(line)
    sys.stdout.write(line + "\n")

Note, if you use the print function, extra newlines will be added - so I used sys.stdout.write

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

You can check this:

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

Upvotes: 0

Neo
Neo

Reputation: 3786

Use regex replacement, maybe?

import re
path = "test.txt"
f = open(path, "r")
data = re.sub(".", "0", f.read())
f.close()
f = open(path, "w")
f.write(data)
f.close()

Upvotes: 1

Related Questions