python 寫檔案編碼問題

2021-07-09 02:18:11 字數 691 閱讀 2033

import urllib.request

import sys
resp=urllib.request.urlopen("")
html=resp.read()
fo=open("test.html","w")
fo.write(html)
fo.close()
python 儲存網頁,後出現如下錯誤

解決方法:

import urllib.request
import sys
resp=urllib.request.urlopen("")
html=resp.read()
fo=open("test.html",mode="w",encoding='utf-8')
fo.write(html.decode('utf-8'))
fo.close()
說明

然後,如果你用的是windows的作業系統,預設呼叫open方法開啟的檔案編碼格式是gbk,

這樣預設儲存的檔案顯示在瀏覽器裡面是亂碼, 因為你頁面內容裡面指定的是utf-8編碼,就是 content="text/html;charset=utf-8" 這個,但是你html檔案編碼為gbk,所以直接顯示亂碼。

檔案的時候,指定儲存的編碼格式為utf-8。

Python 讀取檔案編碼問題

讀取csv檔案,有時可能會遇見編碼問題。join 是自動在 字串 陣列之間加上 放在set裡用來去重 def csvprocess self flag true 去重處理 產國 大類 型別 with open self.cms data path,encoding utf 8 sig as f re...

Python檔案中文編碼問題

需要讀取utf 8編碼的中文檔案,先利用sublime text軟體將它改成無dom的編碼,並且在第一行寫 encoding utf 8 然後用以下 with codecs.open note path,r utf 8 as f line f.readline print line 這樣就可以正確地...

python讀取csv檔案編碼問題

使用utf 8編碼開啟csv檔案時候報錯,如下 fo open 2.csv r encoding utf 8 無效方法 使用python讀取含有中文的csv檔案的時候常常遇到編碼錯誤,因此就想把csv檔案編碼改為utf 8編碼方式,用excel開啟另存為utf 8格式沒法解決問題,可以採用以下方法 ...