[問題] 載入txt檔 中文字會有亂碼

看板Ruby作者 (花)時間8年前 (2015/07/12 18:23), 8年前編輯推噓2(205)
留言7則, 2人參與, 最新討論串1/1
各位前輩們好 想請問說 # encoding: UTF-8 abc = Array.new() abc[0] = "電腦" File.open("database.txt", "a") {|file| file.write(abc[0])} txt = File.open("database.txt") puts txt.read() 當我執行這段程式碼時,結果會跑出亂碼 有甚麼方法可以解決嗎? 謝謝大家 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.173.128.189 ※ 文章網址: https://www.ptt.cc/bbs/Ruby/M.1436696612.A.A34.html

07/12 20:11, , 1F
puts txt.read.encode('utf-8')
07/12 20:11, 1F
它有錯誤訊息: 'encode': "\xE8" followed by "\x85" on CP950 可以請問這是甚麼意 思嗎? google過了還是不懂 不好意思新手問題多多 ※ 編輯: philip80220 (59.127.241.162), 07/12/2015 21:36:11

07/12 22:48, , 2F
你要先確認檔案database.txt的編碼
07/12 22:48, 2F

07/12 22:49, , 3F
若要指定編碼可以用 "a:utf-8" 這種用法來指定
07/12 22:49, 3F

07/12 22:51, , 4F
Windows應該是用BIG5 所以開檔設成"a:big5"試試看
07/12 22:51, 4F

07/12 22:52, , 5F
應該是你把UTF-8編碼字串append到了Big5編碼檔案去了
07/12 22:52, 5F

07/12 22:52, , 6F
你應該file.write(abc[0].encode('big5'),或是把檔案
07/12 22:52, 6F

07/12 22:52, , 7F
整個改成UTF-8編碼
07/12 22:52, 7F
文章代碼(AID): #1Lea0aeq (Ruby)