作者GoodByeLove (Fantastic!)
看板Python
標題[問題] for迴圈讀檔處理
時間Tue May 13 17:08:56 2014
最近剛開始學Python, 想請問版上前輩幾個問題
1. 有沒有辦法讀檔案後, 利用","做區分去讀一個一個的string?
p.s. 我大致寫了另一個在
http://codepad.org/P1b5A7dd
檔案結構如同buf = "x503, 00x1, 60x2, x305, 503x, x503, 60x1,...."
想要的結果是符合x503的都會出現在result, 反之就在result2
2. 我以下的寫法都只會比對第一個string, 後面的就都不會比了 @@
不知道問題出在哪? 希望大大指點一下
buf = open("input.txt", "rb")
ori = buf.read().strip().split(",")
temp = map(str, ori)
result = []
result2 = []
number = 0
for teststr in temp:
teststr = teststr.strip() #加上這行先把空白濾掉
if teststr != '':
if teststr == 'x503':
result.append(teststr)
number = number+1
else:
result2.append(teststr)
number = number+1
else:
break
print result
print result2
print number
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 39.14.172.234
※ 文章網址: http://www.ptt.cc/bbs/Python/M.1399972142.A.E07.html
→ KSJ:沒實作過 但看起來後面的503前面有個空格吧 像這樣 " x503" 05/13 17:21
→ math99:strip 應該用在 loop 裡面 05/13 17:23
→ GoodByeLove:感謝提醒。改了後正確囉!謝謝 05/13 18:06
※ 編輯: GoodByeLove (39.14.172.234), 05/13/2014 18:15:37