我在 python 编程,但我坚持制作二进制文件

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

所以我想在Python中制作一个二进制文件,但它给出了一个错误

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

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

有人可以帮忙吗?

如果以二进制方式打开文件,则必须将字符串编码为字节:

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

或使用 b 作为字符串的前缀:

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