You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows11 Python3.9执行f.write报TypeError需bytes而非str如何解决

报错原因

你以wb(二进制写入)模式打开了crclist文件,该模式仅支持写入字节类型数据,但你拼接生成的buf是字符串类型,因此触发类型错误。

解决方法

提供两种可行方案,按需选择即可:

方案1:字符串编码为字节(最小改动,无需修改文件打开模式)

将写入行的buf调用encode()方法转成字节后再写入,修改后的代码段如下:

# generate crclist
print("Generating crclist:")
with open(output_crclist, "wb") as f:
    for elem in file_list:
        buf = "%s %d %d %d %s\n" % (elem["crc32"], elem["size"], elem["mtime1"], elem["mtime2"], elem["real_path"])
        f.write(buf.encode('utf-8')) # 新增encode转字节
        print(buf.replace("\n", ""))

方案2:改为文本模式写入

如果crclist是普通文本配置文件,直接把文件打开模式从wb改为w即可,还可以显式指定编码避免跨系统乱码:

# generate crclist
print("Generating crclist:")
# 把wb改成w,指定utf-8编码
with open(output_crclist, "w", encoding="utf-8") as f:
    for elem in file_list:
        buf = "%s %d %d %d %s\n" % (elem["crc32"], elem["size"], elem["mtime1"], elem["mtime2"], elem["real_path"])
        f.write(buf)
        print(buf.replace("\n", ""))

选择说明:如果后续读取crclist的程序要求文件是二进制格式,选方案1;如果是普通文本读取,选方案2更便于后续手动查看编辑。

内容的提问来源于stack exchange,提问作者Raul6969

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:06:03