[問題] for迴圈讀檔處理

看板Python作者 (Fantastic!)時間11年前 (2014/05/13 17:09), 11年前編輯推噓0(003)
留言3則, 3人參與, 最新討論串1/1
最近剛開始學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

05/13 17:21, , 1F
沒實作過 但看起來後面的503前面有個空格吧 像這樣 " x503"
05/13 17:21, 1F

05/13 17:23, , 2F
strip 應該用在 loop 裡面
05/13 17:23, 2F

05/13 18:06, , 3F
感謝提醒。改了後正確囉!謝謝
05/13 18:06, 3F
※ 編輯: GoodByeLove (39.14.172.234), 05/13/2014 18:15:37
文章代碼(AID): #1JSU4ku7 (Python)
文章代碼(AID): #1JSU4ku7 (Python)