开发者

Writing Strings to files in python

开发者 https://www.devze.com 2022-12-24 19:30 出处:网络
I\'m getting the following error when trying to write a string to a file in pythion: Traceback (most recent call last):

I'm getting the following error when trying to write a string to a file in 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

I basically have a string class, which contains a 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__(s开发者_StackOverflow中文版elf):
        return str(self.value)

Furthermore, I'm calling that class like this (where variable is an array of _off_str objects:

def write(self, file):
    for variable in self.variables:
        variable.write(file)

I have no idea what is going on. I've seen other python programs writing strings to files, so why can't this one?

Thank you very much for your help.

Edit: It looks like I needed to state how I opened the file, here is how:

file = open(filename, 'wb')
primary.write(file)
file.close()


What version of Python are you using? In Python 3.x a string contains Unicode text in no particular encoding. To write it out to a stream of bytes (a file) you must convert it to a byte encoding such as UTF-8, UTF-16, and so on. Fortunately this is easily done with the encode() method:

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

Another example, writing UTF-16 to a file:

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

Finally, you can use Python 3's "automagic" text mode, which will automatically convert your str to the encoding you specify:

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


I suspect you are using Python 3 and have opened the file in binary mode, which will only accept bytes or buffers to be written into it.

Any chance we could see the code that opens up the file for writing?


edit: Looks like that is indeed the culprit.


I'm not seeing you open the file first:

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


I see in you comment you mentioned that you did

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

That means you're opening the file to write in binary (so just leave out the b flag).


How did you open the file ?

According to the error message, I'll guess :

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

If you want to use strings, you must use :

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

If you use "b", files will expect binary data, and you are writing self.value which is a string.

By the way, don't use file" as a variable name as it hides the file built-in Python object.

0

精彩评论

暂无评论...
验证码 换一张
取 消