python - 我正在用 python 编程,但我一直在制作二进制文件

标签 python file-io binary

所以我想用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!')

关于python - 我正在用 python 编程,但我一直在制作二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70394956/

相关文章:

python - Optuna LightGBM LightGBMPruningCallback

python - 在 "pip3 install cython"之后在 Ubuntu 22.04 上找不到 cythonize

c++ - 我如何在 C++ 中将数字读入输出文件

c++ - 写入二进制 C++ 错误

c - 从C中的文件读取

python - 将纪元以来的天数转换为日期

python - 在 Python 字典中找到最大的键

file-io - 在 Clojure 中拖尾文件?

java - 为什么我们使用基数 32 或基数 64 来表示数据而不是 0 和 1?

r - 如何用零替换数字向量中的非二进制(0/1 除外)字符(在 R 中)?