guiNachos
guiNachos

Reputation: 107

IndexError message in Python using 'with' statement

I have input and output variables assigned to a function definition to grab entries from a GUI, input(read) a .txt file and create(write) an output .txt file that will split some columns of data specifically below:

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])

Compiled I get "IndexError: list index out of range", an output .txt file did generate but there is no column of data in it. What happened?

Upvotes: 1

Views: 139

Answers (2)

Phil Cooper
Phil Cooper

Reputation: 5877

Common error with things like that is a file that ends with a "\n" Look for an empty last line.

Upvotes: 1

Eli Stevens
Eli Stevens

Reputation: 1447

It's highly likely that the columns list has fewer than 4 elements, and so the columns[3] in the last line is raising the IndexError. Without knowing what line is, it's hard to tell. Make the last line this to get some debugging information:

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

Upvotes: 2

Related Questions