用python编写字符串到文件

2024-04-26 18:21:46 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试将字符串写入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()

Tags: 文件字符串inpyselfvaluedefline
3条回答

我没看到你先打开文件:

file_handler = open(path)
file_handler.write(string)
file_handler.close()

你在用什么版本的Python?在Python3.x中,字符串包含没有特定编码的Unicode文本。要将其写入字节流(文件),必须将其转换为字节编码,如UTF-8、UTF-16等。幸运的是,使用encode()方法很容易做到这一点:

Python 3.1.1 (...)
>>> s = 'This is a Unicode string'
>>> print(s.encode('utf-8'))

另一个例子,将UTF-16写入文件:

>>> f = open('output.txt', 'wb')
>>> f.write(s.encode('utf-16'))

最后,您可以使用Python 3的“automagic”文本模式,它将自动将您的str转换为您指定的编码:

>>> f = open('output.txt', 'wt', encoding='utf-8')
>>> f.write(s)

我怀疑您使用的是Python 3,并且已经以二进制模式打开了该文件,它只接受要写入其中的字节或缓冲区。

我们有没有可能看到打开文件进行编写的代码?


编辑:看来这确实是罪魁祸首。

相关问题 更多 >