Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: TypeError: can't write str to text stream

Tags:

python

io

I must be doing something obviously wrong here. But what is it, and how do I fix?

Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import io
>>> f1 = io.open('test.txt','w')
>>> f1.write('bingo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\appl\python\2.6.5\lib\io.py", line 1500, in write
    s.__class__.__name__)
TypeError: can't write str to text stream

edit: In my real application, I won't have a constant string, I'll have a regular string... if unicode is the issue, how do I convert to what io.open requires?

like image 985
Jason S Avatar asked Dec 22 '10 19:12

Jason S


2 Answers

The io module is a fairly new python module (introduced in Python 2.6) that makes working with unicode files easier. Its documentation is at: http://docs.python.org/library/io.html

If you just want to be writing bytes (Python 2's "str" type) as opposed to text (Python 2's "unicode" type), then I would recommend you either skip the io module, and just use the builtin "open" function, which gives a file object that deals with bytes:

>>> f1 = open('test.txt','w')

Or, use 'b' in the mode string to open the file in binary mode:

>>> f1 = io.open('test.txt','wb')

Read the docs for the io module for more details: http://docs.python.org/library/io.html

like image 94
Edward Loper Avatar answered Oct 18 '22 06:10

Edward Loper


Try:

>>> f1.write(u'bingo')      # u specifies unicode

Reference

like image 13
user225312 Avatar answered Oct 18 '22 07:10

user225312