Python寫入csv檔案中文亂碼問題

2021-10-04 16:18:00 字數 1164 閱讀 8983

今天用python3寫入csv檔案的時候,出現中文亂碼的問題,但是寫入txt檔案顯示正常。

寫入txt

record_file =

open

('./database/githubdaily_weibo.txt'

, mode=

'a', encoding=

'utf-8'

)record_file.write(

'發布時間,終端,內容\n'

)

顯示正常,編碼為 utf-8

寫入csv

record_file =

open

('./database/githubdaily_weibo.csv'

, mode=

'a', encoding=

'utf-8'

)record_file.write(

'發布時間,終端,內容\n'

)

顯示亂碼

只需要將encoding='utf-8'改為encoding='utf-8-sig'

寫入txt

record_file =

open

('./database/githubdaily_weibo.txt'

, mode=

'a', encoding=

'utf-8-sig'

)record_file.write(

'發布時間,終端,內容\n'

)

顯示正常,編碼為 utf-8-bom

寫入csv

record_file =

open

('./database/githubdaily_weibo.csv'

, mode=

'a', encoding=

'utf-8-sig'

)record_file.write(

'發布時間,終端,內容\n'

)

顯示正常

成功!

Python將中文寫入CSV檔案編碼問題

目標 將中文資料存入到csv格式的 中。方法 在建立csv 時,預先設定編碼格式。如果設定為utf 8,則會出現如圖所示亂碼。如果沒有設定編碼格式,執行python則會報錯 unicodeencodeerror gbk codec can t encode character u0001f923 i...

python寫入csv檔案中文亂碼解決方案

問題 最近處理資料時需要將txt檔案轉化成csv格式,txt中正常儲存顯示的中文在寫入到csv檔案時變成了亂碼,檔案的編碼未能正確處理中文,需要在寫入csv檔案時指定編碼。解決方法 csvfile file data.csv wb display chinese correctly csvfile....

python匯出寫入csv檔案中文亂碼 親測

最近處理mongodb中的資料。要將mongo中的資料匯入到csv檔案中。正常寫入csv檔案後。在pycharm中檢視中文正常顯示。但用office開啟csv後,中文卻顯示亂碼。以下方法親測有效 with codecs.open test.csv w utf 8 sig as csvfile 將 u...