python 如何把 utf - 8 字符串写入文件中_心若止水_百度空间
python 如何把 utf - 8 字符串写入文件中2012-01-11 0:49
from:http://stackoverflow.com/questions/934160/write-to-utf-8-file-in-python
1、open file and write
import codecs file=codecs.open("lol","w","utf-8") file.write(u"\u5e10\u53f7\u4e0d\u5b58\u5728")file.close()
2、use pile,but you're careful, and you can see meanother article
http://hi.baidu.com/leejun_2005/blog/item/d7d4a40b0c869e0194ca6bac.html
3、关于 python utf-8 的详细介绍请见:
How to Use UTF-8 with Python
http://www.evanjones.ca/python-utf8.html
4、Example:
dict_temp = {xxx}
dict_temp_new = {}
for key in dict_temp:
value = dict_temp[key]
if type(key)==types.UnicodeType:
key = key.encode('utf-8')
if type(value)==types.UnicodeType:
value = value.encode('utf-8')
dict_temp_new[key] = value
#
dict_temp = dict_temp_new_____________________________________________________
import locale import sys import sys, os import types from anyvalue import * from mysql_base import * from debug_utils import * import urllib2 import re import urllib import codecs locale.setlocale(locale.LC_ALL, '') lang, encoding = locale.getdefaultlocale() print 'Locale encoding :', encoding sys.stdout = codecs.getwriter(encoding)(sys.stdout) qq = row[0] email = temp_dict.get("email", 'null') name = temp_dict.get("name", 'null') phone = temp_dict.get("phone", 'null') type_str = temp_dict.get("type", 'null') urlstring = "http://8.8.8.8/qplus/user123?qq=%s&email=%s&name=%s&phone=%s&type=%s" %(qq,email,name.decode('utf-8'),phone,type_str) print urlstring f.write(urlstring.encode("utf-8")+ "\n") url = "http://8.8.8.8/qplus/adduser?" search = [('qq',qq),('email',email),('name',name),('phone',phone),('type',type_str)] getString = url + urllib.urlencode(search) print getString try: r = urllib2.Request(getString) res = urllib2.urlopen(r, None, 10) a = res.readlines() print str(qq) + " : " + str(email) + " : return_code:" + str(eval(a[0])['return_code']) + "" + eval("u"+ "'" + eval(a[0 ])['return_msg'].replace("\\\\", "\\") + "'") except Exception,e: print str(e) print getString