Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Strings to files in python

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__(self):
        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()
like image 749
Leif Andersen Avatar asked Mar 22 '10 19:03

Leif Andersen


People also ask

How do you write data to a file in Python?

To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

Can I write to a file in Python?

Python provides us with two methods to write into text files: write() method for inserting a string to a single line in a text file. writelines() method for inserting multiple strings from a list of strings to the text file simultaneously.


1 Answers

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)
like image 192
Nate Avatar answered Oct 03 '22 09:10

Nate