2012-03-08 33 views
1

我有分配給函數定義的輸入和輸出變量,以從GUI獲取條目,輸入(讀取).txt文件並創建(寫入)輸出.txt文件,拆分下面具體數據的一些列:在Python中使用'with'語句的IndexError消息

def runTransferDialog(): 
    e1, e2 = StringVar(), StringVar() 
    PackDialog(e1, e2) 
    input, output = e1.get(), e2.get()   # GUI entries assigned to variables 
    if input !='' and output !='': 
     with open(input, 'r') as input1:  # read input .txt file 
      with open(output, 'w') as output1: # write input .txt file 
       for line in input1: 
        columns = line.strip().split() 
        output1.write('{:8}{:8}\n'.format(columns[0], columns[3]) 

編譯我得到「IndexError:列表索引超出範圍」,輸出.txt文件並生成,但沒有在它的數據列。發生了什麼?

+2

請不要使用'input'作爲變量名稱。它會隱藏內置函數['input()'](http://docs.python.org/library/functions.html#input)。 – jathanism 2012-03-08 01:30:36

回答

2

這是極有可能的是,columns名單少於4個元素,因此,在最後一行columns[3]是提高IndexError。不知道line是什麼,很難說。讓最後一行此得到一些調試信息:有這樣的事情

try: 
    output1.write('{:8}{:8}\n'.format(columns[0], columns[3]) 
except IndexError, e: 
    print repr(line) 
    # Alternatively 
    #output1.write("Error: " + repr(line)) 
    raise 
+0

很酷的調試技巧謝謝。 – guiNachos 2012-03-08 01:47:49

1

常見的錯誤是用「\ n」個 尋找一個空的最後一行結尾的文件。