Python byte literal

Viewed 757

I supect this a bit of a python newbie question, but how do you write a single byte (zero in this case) to a file?

I have this code:

f = open("data.dat", "wb")
f.write(0)
f.close()

But on the write line it is giving the error:

TypeError: a bytes-like object is required, not 'int'

I guess I need to replace 0 with a byte literal, but can't figure out the syntax. All my searches are telling me about converting strings to bytes. I tried 0B but that didn't work.

2 Answers

You are trying to write the integer 0. That's a Python object.

I suppose you want to write the null byte. In that case, issue f.write(b'\0').

b'\0' is short for b'\x00'.

Related