今天在学习Python的时候,报了这样一个错误,我先申明一下我用的python版本是3.7。
具体错误如下:
F:\Python3.7.0\python.exe F:/python/21.py
<class 'str'>
Traceback (most recent call last):
File "F:/python/21.py", line 10, in <module>
os.write(fd, str)
TypeError: a bytes-like object is required, not 'str'
上面最后一句话的意思是“类型错误:需要类似字节的对象,而不是字符串”。

报错原因:
在这里,python3和Python2在套接字返回值解码上有区别。
解决办法:
解决办法非常的简单,只需要用上python的bytes和str两种类型转换的函数encode()、decode()即可!
- str通过encode()方法可以编码为指定的bytes;
- 反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法;
因此:我只需要把上图中的代码改成下面的即可!
import os,sys
#打开文件
fd = os.open('foo.txt',os.O_RDWR|os.O_CREAT)
str = 'this is test'
str = str.encode()
#写入字符串
os.write(fd,str)
#关闭文件
os.close(fd)
print('关闭文件成功!')
还有一种方法也可以实现,具体代码如下:
str = 'this is test'
os.write(fd,bytes(str,'UTF-8'))
|