2012-03-08 2 views
1

GUIからエントリを取得し、.txtファイルを入力(読み込み)し、出力.txtファイルを作成(書き込み)するために、関数定義に割り当てられた入出力変数があります。 「はIndexErrorを:範囲外のリストインデックス」私が手にコンパイル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]) 

:以下に具体的にデータの一部の列を分割し、発生しました.txtファイルの出力が、その中にデータのない列はありません。何が起こった?

+2

変数名に 'input'を使用しないでください。組み込み関数['input()'](http://docs.python.org/library/functions.html#input)をシャドウします。 – jathanism

答えて

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

1

一般的なエラーは、「\ n」は空の最後の行のための ルックで終わるファイルです。

関連する問題