【发布时间】:2011-01-30 12:26:27
【问题描述】:
尝试将字符串写入 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
我基本上有一个字符串类,其中包含一个字符串:
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()
【问题讨论】:
-
我回答了你的问题,但我自己也有一个。为什么要在 Python 中编写自己的字符串类,而 Python 本身内置了几个非常强大的类?
-
或者,更强烈地说。请不要发明自己的字符串类。这种事情使软件无法维护。
-
我不想这样做,这只是包中其他文件的做法。最后,我同意你的看法,觉得真的很傻,直接撕了。我们会看看是否有人投诉。
-
"包中的其他文件?"你的意思是每个其他模块都发明了自己的字符串类?你在做什么?
-
blender 中的导出脚本。也可能只是我不理解他们。我特别关注 export_3ds 的,如果你那么在意的话。
标签: python string file io python-3.x