8

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.

Martin Brown
  • 24,692
  • 14
  • 77
  • 122

2 Answers2

6

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

timgeb
  • 76,762
  • 20
  • 123
  • 145
1

You may be better off converting int to byte this way:

b = bytes([0])

Alternatively, you may be better off using the struct library:

https://docs.python.org/2/library/struct.html

You may gain looking at Converting int to bytes in Python 3

Tarik
  • 10,810
  • 2
  • 26
  • 40
  • Both Python 2 (`'\0'`) and Python 3 (`b'\0'`) have byte literals. (Python 2 *called* the type `str`, but fixing the string-vs-bytes dichotomy was one of the major goals of Python 3.) – chepner May 13 '20 at 17:58
  • @chepner I figured it out and fixed my answer. – Tarik May 13 '20 at 18:03