在Python中将字符串写入文件

13 投票
5 回答
43945 浏览
提问于 2025-04-15 20:43

我在用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()

5 个回答

2

我没有看到你先打开文件:

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

你正在使用哪个版本的Python?在Python 3.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的“自动魔法”文本模式,它会自动把你的str转换成你指定的编码:

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

我猜您是在使用Python 3,并且是以二进制模式打开文件,这样的话只能写入字节或缓冲区的数据。

能不能让我们看看您用来打开文件进行写入的代码呢?


补充:看起来这确实是问题所在。

撰写回答