记录学习python遇到的问题,也分享给大家,大家共同进步。。。
问题点:TypeError: a bytes-like object is required, not ‘str’
百度翻译:TypeError:需要类似字节的对象,而不是“str”
个人理解:需要类似的字符对象,而不是字符串。
错误代码如下:
#!/usr/bin/python3
#-- coding: UTF-8 --
import os, sys
打开文件
fd = os.open(r"C:\Users\ququ\Desktop\python\foo1.txt", os.O_RDWR|os.O_CREAT )
复制文件描述符
d_fd = os.dup( fd )
使用复制的文件描述符写入文件
os.write(fd, “This is test”)
关闭文件
os.closerange( fd, fd)
print (“关闭所有文件成功!!”)
正确代码如下:
#!/usr/bin/python3
#-- coding: UTF-8 --
import os, sys
打开文件
fd = os.open(r"C:\Users\ququ\Desktop\python\foo1.txt", os.O_RDWR|os.O_CREAT )
复制文件描述符
d_fd = os.dup( fd )
使用复制的文件描述符写入文件
os.write(fd, “This is test”.encode())
关闭文件
os.closerange( fd, fd)
print (“关闭所有文件成功!!”)
问题点对比:
错误:os.write(fd, “This is test”)
正确:os.write(fd, “This is test”.encode())
也可是先定义:
str=“This is test”;
os.write(fd, str.encode())
总结:不论怎样,都得使用字符对象,而不是直接使用字符串;
TypeError Traceback (most recent call last)
in
9 # d_fd = os.dup( fd )
10 # 使用复制的文件描述符写入文件
—> 11 os.write(fd, “This is test”)
12
13 # 关闭文件
TypeError: a bytes-like object is required, not ‘str’