Re: [問題] 輸出中文text檔案
我不知道你要做什麼,但是你的程式中有許多不恰當的做法
我的方法
input_filename = 'address.txt'
with open(input_filename, 'r') as input_file:
with open('check.txt', 'w') as output_file:
for line in input_file.read().split('\n'):
output_file.write(line.split(',')[1] + '\n')
如果你讀和寫的中文編碼都是big5,那不需要做什麼處理。
※ 引述《ob556 (^o^OoB)》之銘言:
: 最近開始接觸python(2.7)
: 嘗試用python讀入一個txt檔
: 內容大致如下:
: 1,台北市松山區
: 2,台北市文山區
: 3.高雄市三民區
: ..............................
: 我要使用split(',')將數字、和地區分開進行一些處理後
: 再輸出儲存至另一個txt檔中
: 現在遇到的問題是我輸出後的txt檔沒辦法正確顯示中文
: 測試程式碼如下:(目前尚未進行處理的部分,只是想測試輸出檔案)
: # -*- coding: Big5 -*-
: import os
之後沒有用到os,不用import
: address = raw_input('欲轉換檔案之檔名(包括.txt, 最好是英文):')
: txtContent=open(address)
: txt=open('check.txt','w')
: c = 0
: for line in txtContent:
textContent為一個file,通常要read或readline來轉成string
: if c == 0:
: c+=1
: continue
c 後來沒有用到,又是為何?
: no,addr = line.split(',')
split後的結果為一個list, 但是(no, addr)是一個tuple
: a = [no,addr]
上兩句等同於a = line.split(',')
: b =str(a)
a為split後的結果,為一個list,不應也不必如此轉成string,
如果有需要轉的地方,也應寫成 b = [str(item) for item in a]
: txt.write(b)
write之後要接string,因為上一步你轉的不好,所以就產生如下的輸出了
: 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: 114.33.249.239
討論串 (同標題文章)
Python 近期熱門文章
PTT數位生活區 即時熱門文章
18
34