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

2812

被折叠的 条评论
为什么被折叠?



