python入門指南(五)編碼問題

2021-10-02 03:00:30 字數 1023 閱讀 7200

1、寫中文檔案亂碼

with io.open(code_log_path,"a+",encoding='utf-8') as f:

f.write(unicode("\xef\xbb\xbf", "utf-8"))

f.write(u'{}\n'.format(ss))

2、python將字串格式的unicode編碼轉換成unicode編碼,如:\u53eb\u6211,需要轉換成中文時有兩種方式:

(1).使用eval:

eval("u"+"\'"+unicodestr+"\'")
(2)使用decode:

str1 = '\u4f60\u597d'  

print str1.decode('unicode_escape')

你好

unicodestr.decode('unicode_escape')  # 將轉義字元\u讀取出來

3、按行讀檔案

with open('order.txt', 'r+') as f:

while true:

ss= f.readline().decode("gbk").encode("utf-8")

if not ss:

break

print ss,

4、一次讀多行

with open('test3.txt', 'r+') as f:

while f:

ss= f.readline()

ss2= f.readline()

5、設定系統預設編碼  

import sys

reload(sys)

sys.setdefaultencoding('utf8')

6、超出utf-8  

with open("./test.log","r+",encoding="iso-8859-1")as f:

python入門指南 Python 入門指南

python 入門指南 release 3.6.3 date dec 10,2017 python 是一門簡單易學且功能強大的程式語言。它擁有高效的高階資料結構,並且能夠用簡單而又高效的方式進行物件導向程式設計。python 優雅的語法和動態型別,再結合它的解釋性,使其在大多數平台的許多領域成為編寫...

Python 入門指南

release 3.6.3 date nov 26,2017 python 是一門簡單易學且功能強大的程式語言。它擁有高效的高階資料結構,並且能夠用簡單而又高效的方式進行物件導向程式設計。python 優雅的語法和動態型別,再結合它的解釋性,使其在大多數平台的許多領域成為編寫指令碼或開發應用程式的理...

python入門指南 小說 Python 入門指南

python 入門指南 release 3.6.3 date dec 10,2017 python 是一門簡單易學且功能強大的程式語言。它擁有高效的高階資料結構,並且能夠用簡單而又高效的方式進行物件導向程式設計。python 優雅的語法和動態型別,再結合它的解釋性,使其在大多數平台的許多領域成為編寫...