不同编码写入文件

不同编码写入文件
用UTF写入文件,解码成UNICODE,然后再编码成GB2312显示
1.
#coding:utf-8

file = 'unicode.txt'

hello_out = "你好 "
f = open(file, 'w')
f.write(hello_out)
f.close()

f = open(file, 'r')
bytes_in = f.read()
f.close()

print bytes_in.decode('utf-8').encode('gb2312')


2.

#coding:gb2312

file = 'unicode.txt'

hello_out = "你好 "
f = open(file, 'w')
f.write(hello_out)
f.close()

f = open(file, 'r')
bytes_in = f.read()
f.close()

print bytes_in

3.
#encoding:utf-8

import urllib

url = 'http://www.iplaypython.com/'

a = urllib.urlopen(url)

tx = a.read().decode('utf8').encode('mbcs')
print tx

4.
#encoding:utf-8

import urllib

url = 'http://www.163.com/'

a = urllib.urlopen(url)

tx = a.read().decode('gbk').encode('mbcs')

print tx




原文地址:https://www.cnblogs.com/highroom/p/10fe10b4f9715a8df8bba3917daac2fc.html