【问题标题】:TypeError: a bytes-like object is required, not 'str', for writing string to fileTypeError:需要一个类似字节的对象,而不是“str”,用于将字符串写入文件
【发布时间】:2021-07-19 09:18:07
【问题描述】:
            for d in range(0,d2.size):
                c2 += str(d2.item(d))
            cf.write(chr(int(c2,2)))

在 cf.write(chr(int(c1,2))) 中出现错误

TypeError: 需要一个类似字节的对象,而不是 'str'

代码在 python 2.x 上运行良好

【问题讨论】:

标签: python python-3.x string byte


【解决方案1】:

在您的评论中,您说您正在使用参数 wb 以字节形式打开文件,但是您尝试将 string 写入导致错误的文件。

要解决这个问题,您只需将字符串转换为字节

for d in range(0,d2.size):
    c2 += str(d2.item(d))
    cf.write(bytes(chr(int(c2,2)), 'utf-8'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多