2021年4月11日 星期日

Python Error - UnicodeDecodeError: 'cp950' codec can't decode

讀檔時 UnicodeDecodeError: 'cp950' codec can't decode

老實說這非常常見,即使你的檔案是用 UTF-8 編寫,而且用 Python3 ( 絕大部分 default 是 utf-8 ),仍會報這個錯。所以要避免程式能在不同平台都能正常使用,讀檔時最好都加上 encoding="utf-8"
    with open("somefile.py", encoding="utf-8") as f:
        f.read()
參考資料 :
1.stackoverflow

Related Posts:

  • Python 遞迴初學最近用 python 刷題 刷到要用 DFS 的題目,想用遞迴去寫才發現 python 沒有指標 看著討論的 python 大神寫的程式碼,發現都是 python 裡的參數都是指標 下面拿一題示範 0947 - Most Stones Removed with Same Row or Column class Solution: def removeStones(self, stones: List[L… Read More
  • Python - sys, os.path 常見的 module 應用 Common python module - sys sys parameter 一些常見系統參數 import sys print(sys.platform) # linux sys.argv 像 c/c++ 的 argv 一樣,可以吃從 command line 傳入的參數。 # test.py 123 456 789 print (argv) … Read More
  • Python UnitTest Unit Test      單元測試有一個通用模式 AAA原則,理解了就可以開始實作 Arrange   : 初始化物件、要用到的參數 Act   : 呼叫要測試的方法 Assert   : 驗證測試結果 Python Unit Test      unittest — Uni… Read More
  • Python Windows 換行符號與 Unix 換行轉換 ( convert CRLF to LF ) Convert CRLF to LF def convertCRLFtoLF(self, filename): WINDOWS_LINE_ENDING = b'\r\n' UNIX_LINE_ENDING = b'\n' with open(filename, "rb") as f: content = f.read() … Read More
  • Python bin() Python bin() bin(10) // 0b1010 type(bin(10)) // <class 'str'> bin(10)[2:] // 1010 … Read More

0 意見:

張貼留言

Popular Posts