1. 程式人生 > >Python 讀寫檔案 中文亂碼 錯誤TypeError: write() argument must be str, not bytes+

Python 讀寫檔案 中文亂碼 錯誤TypeError: write() argument must be str, not bytes+

今天使用Python向檔案中寫入中文亂碼,程式碼如下:

fo = open("temp.txt", "w+")
str = '中文'
fo.write(str)
fo.close()
  
  • 1
  • 2
  • 3
  • 4

後來指定寫入字串的編碼格式為UTF-8,出現錯誤TypeError: write() argument must be str, not bytes

fo = open("temp.txt", "w+")
str = '中文'
str = str.encode('utf-8')
fo.write(str
) fo.close()
  • 1
  • 2
  • 3
  • 4
  • 5

網上搜索才發現原來是檔案開啟方式有問題,把之前的開啟語句修改為用二進位制方式開啟就沒有問題

fo = open("temp.txt", "wb+")
  
  • 1

完整程式碼如下:

fo = open("temp.txt", "wb+")
str = '中文'
str = str.encode('utf-8')
fo.write(str)
fo.close()
  
  • 1
  • 2
  • 3
  • 4
  • 5

且中文不會亂碼
產生問題的原因是因為pickle儲存方式預設是二進位制方式

今天使用Python向檔案中寫入中文亂碼,程式碼如下: