问题描述
我必须在这里做一些明显错误的事情。但它是什么,我该如何解决?
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
编辑:在我的实际应用中,我将不会有一个常量字符串,我将有一个常规字符串...如果unicode是问题,我如何转换为io.open需要的?
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?
推荐答案
io
模块是一个相当新的python模块(在Python 2.6中引入),可以更轻松地处理unicode文件。其文档位于:
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
如果你只想写字节(Python 2的str类型)而不是文本(Python 2的unicode类型),那么我建议你跳过 io
模块,只需使用内置的open函数,它提供一个处理字节的文件对象:
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')
或者,使用'b'in用于以二进制模式打开文件的模式字符串:
Or, use 'b' in the mode string to open the file in binary mode:
>>> f1 = io.open('test.txt','wb')
阅读文档io模块了解更多详情:
Read the docs for the io module for more details: http://docs.python.org/library/io.html
这篇关于python:TypeError:无法将str写入文本流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!