Python报“TypeError: a bytes-like object is required, not ‘str’ ”解决办法

今天在学习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'

上面最后一句话的意思是“类型错误:需要类似字节的对象,而不是字符串”。

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 fujieace.com test'
str = str.encode()

#写入字符串
os.write(fd,str)

#关闭文件
os.close(fd)

print('关闭文件成功!')

 

其它解决方法

还有一种方法也可以实现,具体代码如下:

str = 'this is fujieace.com test'
os.write(fd,bytes(str,'UTF-8'))
    A+
发布日期:2018年11月06日 21:31:20  所属分类:Python
最后更新时间:2021-06-04 21:04:02
付杰
  • ¥ 159.0元
  • 市场价:599.0元
  • ¥ 999元
  • 市场价:4999元
  • ¥ 79.0元
  • 市场价:99.0元
  • ¥ 99.0元
  • 市场价:129.0元

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: