在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ windows下python3 open函數(shù)編碼問題。

windows下python3 open函數(shù)編碼問題。

with open('1.txt')as f:
    for i in f.readlines():
        needed=i.split(':',1)
        with open('need.txt','a')as f1:
            f1.write('{}:{}'.format(needed[0],needed[1]))

這樣會報錯,'gbk' codec can't decode byte
只能加上

with open('1.txt',encoding='utf-8')as f:
    for i in f.readlines():
        needed=i.split(':',1)
        with open('need.txt','a')as f1:
            f1.write('{}:{}'.format(needed[0],needed[1]))

指定編碼方式才可以,然后輸出的need.txt里面有亂碼,要轉(zhuǎn)化成GBK編碼才能正常顯示。1.txt編碼方式是utf-8。
系統(tǒng)的默認(rèn)編碼是utf-8
圖片描述

有什么辦法讓open函數(shù)默認(rèn)就是utf8編碼呢,而不需要手動指定。

回答
編輯回答
夢囈

默認(rèn)utf8,是myopen這個意思么?

myopen = lambda i: open(i,encoding='utf-8')
with myopen ('1.txt') as f:
    with open('need.txt','a')as f1:
        for i in f.readlines():
            needed=i.split(':',1)
            f1.write('{}:{}'.format(needed[0],needed[1]))

還有給你調(diào)了一下順序,不要在循環(huán)里使用open,會頻繁打開和關(guān)閉文件,效率低下

2018年2月23日 11:32