Lei*_*sen 12 python string io file python-3.x
尝试将字符串写入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
Run Code Online (Sandbox Code Playgroud)
我基本上有一个字符串类,其中包含一个字符串:
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)
Run Code Online (Sandbox Code Playgroud)
此外,我正在调用这个类(其中变量是_off_str对象的数组:
def write(self, file):
for variable in self.variables:
variable.write(file)
Run Code Online (Sandbox Code Playgroud)
我不知道发生了什么事.我见过其他python程序将字符串写入文件,为什么不能这样呢?
非常感谢您的帮助.
编辑:看起来我需要说明我是如何打开文件的,这是如何:
file = open(filename, 'wb')
primary.write(file)
file.close()
Run Code Online (Sandbox Code Playgroud)
Nat*_*ate 20
您使用的是哪个版本的Python?在Python 3.xa中,字符串包含没有特定编码的Unicode文本.要将其写入字节流(文件),必须将其转换为字节编码,如UTF-8,UTF-16等.幸运的是,这可以通过以下encode()方法轻松完成:
Python 3.1.1 (...)
>>> s = 'This is a Unicode string'
>>> print(s.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)
另一个例子,将UTF-16写入文件:
>>> f = open('output.txt', 'wb')
>>> f.write(s.encode('utf-16'))
Run Code Online (Sandbox Code Playgroud)
最后,您可以使用Python 3的"自动"文本模式,它将自动转换str为您指定的编码:
>>> f = open('output.txt', 'wt', encoding='utf-8')
>>> f.write(s)
Run Code Online (Sandbox Code Playgroud)