python无法写入txt_python:TypeError:无法将str写入文本流

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 "", line 1, in

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?

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值