2014-11-06 62 views
0

。這是我的程序Python的IndexError超出範圍

#!/usr/bin/python 
import sys 
fn=sys.argv[1] 
dt=open(fn).readlines() 
    for ln in dt: 
    fd=ln.split() 
    cntw=fd[1].count("W") 
    print cntw 

它完全讀取該文件,但在最後給出了錯誤:

Traceback (most recent call last): 
    File "./task0.py", line 7, in <module> 
    cntw=fd[1].count("W") 
IndexError: list index out of range 

這是爲什麼,什麼我需要改變嗎?

+0

點,如果你告訴我們,文件的內容,將是很好的 – Hackaholic 2014-11-06 20:59:33

回答

2

你的最後一行是空的,跳過它:

for ln in dt: 
    fd = ln.split() 
    if not fd: 
     continue 

一個空行的結果是空列表:

>>> ''.split() 
[] 

not fd測試爲真空集裝箱。

請注意,您不必首先將所有行讀入內存;放棄readlines()調用並直接在打開的文件對象上循環;使用with聲明已經做時Python會自動爲你關閉它:

with open(fn) as fileobj: 
    for ln in fileobj: 
     fd = ln.split() 
     if not fd: 
      continue 
     cntw = fd[1].count("W") 
     print cntw 
+0

什麼是隻有一條線有一個元素? '如果len(fd)<2'確保至少有兩個元素 – 2014-11-06 21:00:00

+0

^Padraic說。使用異常處理好得多。 – mdadm 2014-11-06 21:06:02

+0

@PadraicCunningham:或許OP *想要*在一行中沒有第二個元素時得到異常?空行通常很好。 – 2014-11-06 21:15:23

1

該文件的內容將有助於瞭解你們怎麼做到的,但這裏是一個更Python的解決方案。您應該使用try和except語句來捕獲異常,並使用with關鍵字(如Martijn Pieters建議的)在完成時自動關閉文件。

此外,這不是20世紀90年代...我會建議使用變量名稱,以瞭解其目的。我不知道你正在嘗試做的,但我做了一些修改,試圖讓整個:)

#!/usr/bin/python 
import sys 
filename = sys.argv[1] 

with open(filename) as datafile: 
    for line in datafile: 
     words = line.split() 

     try: 
      wcount = words[1].count("W") 
     except IndexError: 
      continue