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

解决办法:
解决办法非常的简单,只需要用上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'))
发布了82 篇原创文章 · 获赞 235 · 访问量 108万+

猜你喜欢

转载自blog.csdn.net/solitudi/article/details/104194292
今日推荐