I was programming in python and I am stuck with making a binary file

Viewed 87

So I want to make a binary file in Python but it gives a error

TypeError: a bytes-like object is required, not 'str' Here is my code

with open('test.binary','wb') as f:
    f = f.write('Hello!')

Can anyone please help?

1 Answers

If you open a file as binary, you have to encode strings as bytes:

with open('test.binary','wb') as f:
    f = f.write('Hello!'.encode())

Or use b as as prefix of your string:

with open('test.binary','wb') as f:
    f = f.write(b'Hello!')
Related