Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试写入文件时缓冲区接口出现问题_Python - Fatal编程技术网

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

Python 尝试写入文件时缓冲区接口出现问题,python,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") 您需要写入字节,而不是Unicode字符串: os.write(fd, b"This is Test") b'…'是一个bytes类型的文本。

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")
您需要写入字节,而不是Unicode字符串:

os.write(fd, b"This is Test")
b'…'
是一个
bytes
类型的文本。您还可以使用
str.encode()
方法对
str
类型进行编码:

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

一般来说,您希望使用而不是使用
os.open()
和低级文件访问。这可以通过使用。

TypeError轻松完成:“str”不支持缓冲区接口