python:TypeError:不能将str写入文本流python


Answers

尝试:

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

参考

Question

我必须在这里做一些明显错误的事情。 但是,这是怎么回事?

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

编辑 :在我真正的应用程序中,我不会有一个常量字符串,我会有一个常规字符串...如果unicode是问题,我该如何转换到io.open需要?




f = open("test.txt", "w")
f.write('bingo')
f.close()

等价地,

with open("test.txt", "w") as f:
    f.write('bingo')

并且块的终止为你关闭文件。