简体   繁体   中英

“list index out of range” when reading data from file

Anyone help to explain why this code gives the error as "list index out of range" ?

I've tried on drawing a graph with text file data.

import matplotlib.pyplot as plt
import csv
x,y = [],[]
with open('text.txt','r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    for row in plots:
        x.append(int(row[0]))
        y.append(int(row[1]))
plt.legend()
plt.show()

Text file

0, 1
1, 3
2, 7
3, 5
....

Result

IndexError                             Traceback (most recent call last)
<ipython-input-5-f3977bc887cc> in <module>()
      5     plots = csv.reader(csvfile, delimiter=',')
      6     for row in plots:
----> 7         x.append(int(row[0]))
      8         y.append(int(row[1]))
      9     plt.legend()

IndexError: list index out of range

As @Megalng pointed out in the comments, the problem is in your text.txt file. I created this file :

12, 12
13, 12
14, 12
15, 13
16, 14
17, 14
18, 15
19, 15
20, 15

and ran your code to get this graph :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM