我在尝试将一个字符串写入Python文件时遇到了以下错误:
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
我基本上有一个字符串类,其中包含一个字符串:
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)
此外,我是这样调用该类的(其中变量是一个 _off_str 对象数组):def write(self, file):
for variable in self.variables:
variable.write(file)
我不知道发生了什么。我已经看到其他Python程序将字符串写入文件,那么为什么这个程序不能呢?
非常感谢您的帮助。
编辑:看起来我需要说明如何打开文件,以下是我的做法:
file = open(filename, 'wb')
primary.write(file)
file.close()