Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

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

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:applpython2.6.5libio.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...