我是Python新手,试图用zer0s覆盖文件的最后128个字节。我做错了什么?
try:
f = open(outputFile, "wb")
for x in range(1, 128):
f.seek(x, 2) # seek relative to end of file
f.write(0)
f.close()
except Exception as e:
sys.exit('Error writing output file ' + str(e))
Error writing output file 'int' does not support the buffer interface
[更新]
运行时没有错误,但是没有写入zer0s(我的意思是\0
(字符串的结尾))
f = open(outputFile, "rb+")
zeros = bytearray(0 * 128)
f.seek(-128, 2) # seek relative to end of file
f.write(zeros)
f.close()
注意:当我尝试f.write('\0'*128)
时,我得到Error writing output file 'str' does not support the buffer interface
答案 0 :(得分:3)
如果你的意思是NULL字节
f.write('\0')
如果你想要实际的零
f.write('0')
如果您的意思是仅覆盖文件的最后部分(而不是追加)
with open('x', 'rb+') as f:
f.seek(-128, 2)
f.write('\0'*128)
答案 1 :(得分:1)
替换这个:
f.write(0)
为:
f.write(str(0))
您需要将其转换为str