尝试写入文件时缓冲区接口出现问题

时间:2015-03-14 09:52:14

标签: python

TypeError:'str'不支持缓冲区接口

import os,stat

fd = os.open("foo.txt",os.O_RDWR|os.O_CREAT)
os.write(fd,"This is Test")
os.closerange(fd,fd)
print("Closed all the files successfully")

1 个答案:

答案 0 :(得分:0)

您需要编写 bytes ,而不是Unicode字符串:

os.write(fd, b"This is Test")

b'...'bytes类型的文字。您还可以使用str方法对str.encode()类型进行编码:

os.write(fd, "This is Test".encode('ascii'))

一般来说,您希望使用io library而不是os.open()和低级文件访问。使用open() function即可轻松完成此操作。