Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python byte literal

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.

like image 656
Martin Brown Avatar asked Oct 16 '22 03:10

Martin Brown


1 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'.

like image 144
timgeb Avatar answered Oct 23 '22 08:10

timgeb