【Python 学习笔记】文件写入时遇到 TypeError 报错

本文探讨了Python中文件写入操作出现TypeError: a bytes-like object is required, not 'str'的问题原因及解决办法。主要介绍了Python3对文本(str)和二进制(bytes)类型的严格区分,并提供了解决方案:通过指定文本模式打开文件或使用str.encode()方法将字符串转换为二进制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在一个简单的文件写入之后:

fileOBJ = open("text1.txt","wb")

fileOBJ.write("It is just a text.\n")

fileOBJ.close()

我遇到了 TypeError 类型的报错:
Traceback (most recent call last):
    File "text.py", line 5, in <module>
	    fileOBJ.write("It is just a text.\n")
TypeError: a bytes-like object is required, not 'str'

查阅了资料之后发现,引起错误的原因是:

python3 在 python2 的基础上对文本和二进制字符进行了更严格的区分。其中文本是 str 类型,而二进制字符是 bytes 类型。

在文件 open() 的参数里如果使用的 mode 是 “b” ,即二进制类型打开,则在文件的 write() 里,传入的应该是二进制字符,所以当我传入 str 时,出现了 TypeError 报错


解决方法:

1. 使用 “t” 类型打开文件:

fileOBJ = open("text1.txt","wt")

fileOBJ.write("It is just a text.\n")

fileOBJ.close()

2. 将传入的 str 参数转换为 bytes 类型:

python3 同时提供了 str 和 bytes 两种类型相互转换的函数:

encode,将str类型编码为bytes。 
decode,将bytes类型转换为str类型。

具体用法为:

fileOBJ = open("text1.txt","wb")

fileOBJ.write("It is just a text.\n".encode())

fileOBJ.close()

针对字符串使用 encode() 函数即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值