[英]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. 文件中的每个字符都将替换为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? 有更好的方法吗?
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()
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: 创建另一个包含0x00
且大小相同的文件:
>>> f = open("/path/to/file", "w")
>>> f.seek(size - 1)
>>> f.write("\x00")
>>> f.close()
>>>
I assumed by 0
, you meant 0x00
byte value 我假设为0
,您的意思是0x00
字节值
Using a regex is probably cleaner, but here is a solution using fileinput
: 使用正则表达式可能更清洁,但这是使用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
注意,如果使用print
功能,将添加额外的换行符-因此我使用sys.stdout.write
You can check this: 您可以检查以下内容:
import fileinput
for line in fileinput.FileInput('/path/to/file', inplace =1):
print len(line)*'0'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.