python 的文件操作

 

 二进制用法

f=open('test.txt','wb')
f.write("汉字\r\n".encode('UTF-8'))
f.write("hello".encode('ascii'))
f.close()

非二进制写法

f=open('test.txt','w')
f.write("汉字\r\n")
f.write("hello")
f.close()

utf-8 和gbk互化

a='hello'.encode('gbk')

print (a)
print (a.decode())


a='hello'.encode('utf-8')
print (a)
print (a.decode())


a='hello'.encode('utf-8').decode().encode('gbk')
print (a)
print (a.decode())

第一种是unicode变gbk。python3里面默认是用unicode,并且所有的编码都用二进制方式来表达。所以看不出来区别但是本质是不同的。比如第三个中间的decode不写就出错了。

第二种是unicode变utf-8

第三种是unicode变utf-8变gbk

posted on 2018-01-06 15:49  张博的博客  阅读(121)  评论(0编辑  收藏  举报

导航