简体   繁体   中英

Index out of range when reading from a csv file

this code reads data from a text file and then proceeds to sort the list created by the program by the number contained in each row (lowest to highest), then the program should match the name entered with one from from the list and then proceed to calculate that persons place.

Here is the code:

def Rank():
  #Declare List
  RankList=[]
  #Opening and reading the file
  with open('GolfInfo.txt','rU') as csvfile:
        reader=csv.reader(csvfile)
        for row in reader:
              #Data added to list
              RankList.append(row)
  #List is sorted by amount of strokes taken (Total) from lowest to highest
  RankList.sort()
  index=0
  Position=0
  RankMessageFull=("")
  for row in RankList:
        #Checks to see if Name is present in the list
        if row[1] == Name.get():
            Position=index+1
            #These if-elif-else statements determine a suitable suffix for the rank
            if Position==1:
                  RankMessageFull=(Position,"st")
                  RankMessage.set(RankMessageFull)
            elif Position==2:
                  RankMessageFull=(Position,"nd")
                  RankMessage.set(RankMessageFull)
            elif Position==3:
                  RankMessageFull=(Position,"rd")
                  RankMessage.set(RankMessageFull)
            else:
                  RankMessageFull=(Position,"th")
                  RankMessage.set(RankMessageFull)

        else:
              index=index+1

The textfile reads:

63,April,"('-', 7)"
69,Betsy,"('-', 1)"
80,Laura,"('+', 10)"
93,Coco,"('+', 23)"

The error occurs in the line:

if row[1] == Name.get():

But I do not know why. The full error message can be seen here:

if row[1] == Name.get():
  IndexError: list index out of range

RankMessage is a Tkinter Stringvar , Name is also a Tkinter StringVar .

It appears that there are lines in the csv file that have only one or fewer items on them. You can avoid adding them to the RankList with the simple change shown below. Also note you should open() csv files using the newline='' option in Python 3.

def Rank():
  #Declare List
  RankList=[]
  #Opening and reading the file
  with open('GolfInfo.txt','rU', newline='') as csvfile:
        reader=csv.reader(csvfile)
        for row in reader:
              #Data added to list if not blank.
              if row:  # ADDED TEST!
                    RankList.append(row)
  #List is sorted by amount of strokes taken (Total) from lowest to highest
  RankList.sort()
  ...

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