看板 Python 關於我們 聯絡資訊
※ 引述《blackspace98 (~我愛夏天~)》之銘言: : 方式一 : 行號1~6為記事本裡面的行號,不輸入 : test.txt : 行號1 /*=================================================== : 行號2 輸入 編號:IP:port : 行號3 ====================================================*/ : 行號4 1:10.1.1.1:1000 : 行號5 2:10.1.1.2:1000 : 行號6 3:10.1.1.3:1000 : 方式一和方式二哪一個我會比較好下手呢? : 但是感覺方式一會比較人性化一點 絕對是第一個方法比較好,方便手動修改, 程式也比較好寫。 ---- f = open('test.txt') linenum = 0 for line in f.readlines(): linenum += 1 if linenum > 3: # 從第四行開始讀資料 num, ip, port = line.split(':') # 以冒號切字串 print num, ip, port # 列印 f.close() ---- 另外,關於設定檔裡的註解,相對於使用 C/C++ 的 Comment 方式 我比較建議使用 Unix 設定檔的慣用方式 也就是該行如果第一個字元是 '#', 那麼該行就是註解 這樣也比較好判斷 也方便任意在各行間加入註解,而不用固定上面幾行為註解 ---- for line in f.readlines(): if line[0] != '#': num, ip, port = line.split(':') print num, ip, port -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 112.104.53.35
blackspace98:謝謝你,我照你建議修改了^^ 01/25 22:15
Pomay:line[0]比對建議用line.startswith('#'), 如果是空字串的話 01/26 19:08
Pomay:line[0]會有error 01/26 19:09