Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

python - List index out of range when importing csv file

import csv
with open('teachers.csv', newline='') as f:
    reader = csv.reader(f)
    df = list(reader)

I am practically new to panda and its functions. I created a csv file with the input as shown below: enter image description here

after I used my variable df as a list i get this error:

Traceback (most recent call last): File "C:UsersUmer NaeemPycharmProjectspythonProjectmain.py", line 356, in data = Data() File "C:UsersUmer NaeemPycharmProjectspythonProjectmain.py", line 39, in init course1 = Course("C1", "325k", [self._instructors[0], self._instructors1], 25) IndexError: list index out of range

heres the code for the course class:

 INSTRUCTORS = df
def __init__(self):
    self._rooms = []
    self._meetingTimes = []
    self._instructors = []
    for i in range(0, len(self.ROOMS)):
        self._rooms.append(Room(self.ROOMS[i][0], self.ROOMS[i][1]))
    for i in range(0, len(self.MEETING_TIMES)):
        self._meetingTimes.append(MeetingTime(self.MEETING_TIMES[i][0], self.MEETING_TIMES[i][1]))
    for i in range(0, len(self.INSTRUCTORS)):
        self._instructors.append(Instructor(self.INSTRUCTORS[i][0], self.INSTRUCTORS[i][1]))

    course1 = Course("C1", "325k", [self._instructors[0], self._instructors[1]], 25)
    course2 = Course("C2", "319k", [self._instructors[0], self._instructors[1], self._instructors[2]], 35)
    course3 = Course("C3", "462k", [self._instructors[0], self._instructors[1]], 25)
    course4 = Course("C4", "464k", [self._instructors[2], self._instructors[3]], 30)
    course5 = Course("C5", "360C", [self._instructors[3]], 35)
question from:https://stackoverflow.com/questions/65938576/list-index-out-of-range-when-importing-csv-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't you want to try pandas implementation of reading csv?

import pandas as pd
df = pd.read_csv('teachers.csv')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...