Forum Archive

IndexError happens in pythonista 3

Kangaroo

import matplotlib.pyplot as plt;

x = [ ];
y = [ ];

readFile = open('xy.txt','r');

for line in readFile:
# file is open with a line in variable 'line'
# do something with this line
print(line);
# split the line based on whitespace
splitUP = line.split();

print('x = ',splitUP[0],'and y = ',splitUP[1]);
# add x and y to the arrays
x.append(splitUP[0]);
y.append(splitUP[1]);

When I run it , it shows IndexError: list index out of the range

Cethric

Without seeing the data or the complete stack trace I can only guess what the issue is. But two possibilities come to mind:
1) line is a white space character so there is nothing to split which results in 2).
2) splitUP has a value of ['xy'] instead of ['x', 'y']
Either way try printing the value of splitUP Without breaking it first. IE print(splitUP) and see what that gives.

Kangaroo

This is my data

2 1.69
3 3.25
4 2.44
5 3.45
6 6.29
7 3.94
8 5.23
9 5.78
10 6.31
11 8.25
12 7.84

Stake:

---------------------------below is my program----------------------------

import matplotlib.pyplot as plt;

x = [ ];
y = [ ];

readFile = open('xy.txt','r');

for line in readFile:

print(line);

splitUP = line.split();

print('x =',splitUP[0],'and y =',splitUP[1]);

x.append(splitUP[0]);
y.append(splitUP[1]);

readFile.close();

plt.plot(x,y);

plt.show();

Kangaroo

Stake:

print('x =',splitUP[0],'and y =',splitUP[1]);
IndexError: list index out of range

JonB

you should use try, then catch the IndexError and print both the line, and the split. You may find that you have a blank line at the end of your file, etc.

JonB

by the way, you might find numpy.loadtxt the best way to read this type of file, especially if you are using this in matplotlub or numpy.

ccc

I would add the line print(splitUP, len(splitUP)) before your current print() line and I would remove all those unnecessary semicolons ;-). I think the others are correct. You have a blank line in your input.

Kangaroo

Thank you guys! I do have a blank line in my file but now it's gone!