尝试将字符串写入pythion中的文件时出现以下错误:
Traceback (most recent call last):
File "export_off.py", line 264, in execute
save_off(self.properties.path, context)
File "export_off.py", line 244, in save_off
primary.write(file)
File "export_off.py", line 181, in write
variable.write(file)
File "export_off.py", line 118, in write
file.write(self.value)
TypeError: must be bytes or buffer, not str
我基本上有一个string类,它包含一个string:
class _off_str(object):
__slots__ = 'value'
def __init__(self, val=""):
self.value=val
def get_size(self):
return SZ_SHORT
def write(self,file):
file.write(self.value)
def __str__(self):
return str(self.value)
此外,我将这样调用该类(其中variable是一个off_str对象数组:
def write(self, file):
for variable in self.variables:
variable.write(file)
我不知道发生了什么事。我见过其他python程序将字符串写入文件,那么为什么这个不能?
非常感谢你的帮助。
编辑:看起来我需要说明我是如何打开文件的,下面是:
file = open(filename, 'wb')
primary.write(file)
file.close()
我没看到你先打开文件:
你在用什么版本的Python?在Python3.x中,字符串包含没有特定编码的Unicode文本。要将其写入字节流(文件),必须将其转换为字节编码,如UTF-8、UTF-16等。幸运的是,使用
encode()
方法很容易做到这一点:另一个例子,将UTF-16写入文件:
最后,您可以使用Python 3的“automagic”文本模式,它将自动将您的
str
转换为您指定的编码:我怀疑您使用的是Python 3,并且已经以二进制模式打开了该文件,它只接受要写入其中的字节或缓冲区。
我们有没有可能看到打开文件进行编写的代码?
编辑:看来这确实是罪魁祸首。
相关问题 更多 >
编程相关推荐