1. 程式人生 > >python2 和python3中分別如何讀取文字

python2 和python3中分別如何讀取文字

# 
# 解決方案  字串的語義發生了變化:
# py2      py3
# str   ->   bytes
# unicode ->  str
# py2.x 寫入檔案前對unicode編,讀入檔案後對二進位制字串解碼
# py3.x open函式指定‘t’的文字模式,encoding指定變編碼格式


# python3中的讀寫
def main():
    s=u'您好'
    print(s.encode('utf8'))
    print(s.encode('gbk'))
    print(s.encode('utf8').decode('utf8'))
    print(s.encode('gbk').decode('gbk'))


    pass
# python2中的讀寫
def main2():
    f=open('py.txt','w')
    s=u'您好'
    f.write(s.encode('gbk'))
    f.close()
    f=open('py.txt','r')
    t=f.read()
    print(t)
    print(t.decode('gbk'))
    f.close()
    pass
# py3讀取文字讀寫
def main3():
    # t就是文字模式
    f=open('py.txt','wt',encoding='utf8')
    s='您好,我愛程式設計'
    f.write(s)
    f.close()
    f=open('py.txt','rt',encoding='utf8')
    t=f.read()
    print(t)
    f.close()
    pass


main3()