看板 Python 關於我們 聯絡資訊
最近開始接觸python(2.7) 嘗試用python讀入一個txt檔 內容大致如下: 1,台北市松山區 2,台北市文山區 3.高雄市三民區 .............................. 我要使用split(',')將數字、和地區分開進行一些處理後 再輸出儲存至另一個txt檔中 現在遇到的問題是我輸出後的txt檔沒辦法正確顯示中文 測試程式碼如下:(目前尚未進行處理的部分,只是想測試輸出檔案) # -*- coding: Big5 -*- import os address = raw_input('欲轉換檔案之檔名(包括.txt, 最好是英文):') txtContent=open(address) txt=open('check.txt','w') c = 0 for line in txtContent: if c == 0: c+=1 continue no,addr = line.split(',') a = [no,addr] b =str(a) txt.write(b) print b txtContent.close() txt.close() 但輸出結果如下: ['\x001\x00', '\x00\xd8\x9a\xc4\x96\x02^\x1fW\xab^2\x00\xef\x8d2\x006\x003\x00_\x86\r\x00\n'] ['\x002\x00', '\x00\xd8\x9a\xc4\x96\x02^^t][W\x886\x004\x00_\x86\r\x00\n'] ['\x003\x00', '\x00\xd8\x9a\xc4\x96\x02^"o\x11l\xef\x8d1\x003\x008\x00_\x86\r\x00\n'] 請問這要如何解決><? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.119.123.123
lulala453:試過 codecs.open(filel, mode, 'utf-8') 來開檔了嗎 11/13 20:46
ob556:試過 但直接出現錯誤:TypeError: an integer is required 11/13 20:52
ob556:我之前未用str()直接在IDLE中print,可以正常顯示中文 11/13 20:54
ob556:但要寫進txt檔中好像要先轉成string?? 11/13 20:55
ee55244:不用轉成字串...可以直接寫進去檔案裡沒問題... 11/13 21:33
ee55244:如果你接下來會用到pyshp的話也是直接寫進去就好 11/13 21:34
chigi:因為list.tostring()沒那麼聰明不會幫你把裡面東西拿出來 11/13 23:36
chigi:變成字串 而是自己變成字串 11/13 23:36
tjjh89017:b.encoding('utf-8') <=這樣呢? 11/15 17:25