代码之家  ›  专栏  ›  技术社区  ›  Leif Andersen

在python中将字符串写入文件

  •  8
  • Leif Andersen  · 技术社区  · 14 年前

    尝试将字符串写入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()
    
    5 回复  |  直到 14 年前
        1
  •  8
  •   Mike Boers    14 年前

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

    我们有机会看到打开文件进行写入的代码吗?


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

        2
  •  18
  •   Nate    14 年前

    您使用的是什么版本的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的“automagic”文本模式,它将自动转换 str 到您指定的编码:

    >>> f = open('output.txt', 'wt', encoding='utf-8')
    >>> f.write(s)
    
        3
  •  2
  •   Manu    14 年前

    我没看到你先打开文件:

    file_handler = open(path)
    file_handler.write(string)
    file_handler.close()
    
        4
  •  1
  •   ChristopheD    14 年前

    我在你的评论中看到你提到过

    file = open('xxx.xxx' ,'wb')
    

    这意味着您要打开文件以写入二进制文件(所以只需将 b 旗帜)

        5
  •  0
  •   Bite code    14 年前

    你是怎么打开文件的?

    根据错误信息,我猜:

    f = open("file", "wb") # b for binary mode
    

    如果要使用字符串,必须使用:

    f = open("file", "w") 
    

    如果使用“b”,文件将需要二进制数据,并且您正在写入 self.value 它是一个字符串。

    顺便说一下,不要用 file “作为变量名,因为它隐藏了 文件 内置的python对象。