看板 Python 關於我們 聯絡資訊
各位大大好 最近小弟在網路上fetch資料時遇上了問題 我抓了一篇中文文章 存在變數content內 接著要把它存成txt檔 file = open("test.txt", "wb") file.write(content) 用記事本去看那個txt檔~正確顯示 按下另存新檔 會得知目前是用utf-8編碼 一切順利 接下來小弟想讓一個字存成一行 也 就 是 像 這 樣 去 存 小弟的code是這樣寫 file = open("test.txt", "wb") for c in content: file.write(c) file.write("\n") 結果得到的檔案會是亂碼 用記事本查看 發現它用ANSI去存 是這邊出錯了吧? 請問我該如何控制txt檔的編碼呢?我要指定他用utf-8 勞煩各位大大解惑了 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.231.24.220
kdjf:len('我') ==> 3 你覺得呢? 09/16 18:37
kdjf:要不然來用python3吧 09/16 18:37
kdjf:想到了,可以用unicode string 09/16 18:44
kdjf:content.decode('utf-8')可以拿到你想要的 09/16 18:45
poopoo888888:k大 file.write()是不是都會以ascii去編碼啊 09/16 19:32
poopoo888888:它在write時顯示error耶 說ascii codec無法去編那些 09/16 19:33
poopoo888888:unicode string 09/16 19:33
poopoo888888:write()的編碼器要怎麼換呢? 09/16 19:33
aknow:python3 open( , mode='w', encoding='utf-8') 09/16 20:15
kdjf:file.write(c.encode('utf-8')) 09/16 20:42
poopoo888888:解決了!非常感謝兩位大大的幫助! 09/17 08:55