0

I an new to Python, trying to overwrite the last 128 bytes of a file with zer0s. What am I doing wrong?

   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

[Update]

this runs with no error, but the zer0s are not written (I mean \0 (end of string))

  f = open(outputFile, "rb+")

  zeros = bytearray(0 * 128)
  f.seek(-128, 2)   # seek relative to end of file
  f.write(zeros)

  f.close()

Note: when I tried f.write('\0'*128) I got Error writing output file 'str' does not support the buffer interface

5
  • Just typecast int 0 to string like this str(0). Commented Nov 18, 2014 at 5:05
  • you should just use bytearray(128) to get the array of NULs Commented Nov 18, 2014 at 5:30
  • 1
    If you are using python3, you'd need to use b'\0'*128 to make a bytes object Commented Nov 18, 2014 at 5:33
  • 1
    Did you get it working? To clarify bytearray(0 * 128) is same as bytearray(0) ie. empty bytearray. Writing that would have no effect of course! Commented Nov 18, 2014 at 6:04
  • I did not know that. Thanks, you can post an answer. However, I have a new problem which I will address in a new question. Commented Nov 18, 2014 at 6:36

2 Answers 2

3

If you mean NUL bytes

f.write('\0')

If you want actual zeros

f.write('0')

If you mean to overwrite just the last part of the file (as opposed to append)

with open('x', 'rb+') as f:
    f.seek(-128, 2)
    f.write('\0'*128)
Sign up to request clarification or add additional context in comments.

1 Comment

I still can't get it to work :=( What is wrong with the updated code?
1

replace this:

f.write(0)

to:

f.write(str(0))

you need to convert it to type str

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.