Home > Enterprise >  IndexError when trying to select the second element of a line from a CSV file
IndexError when trying to select the second element of a line from a CSV file

Time:09-19

import csv

list = []

with open('games.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)

    for row in reader:
        cond = int(row['white_rating']) - int(row['black_rating'])

        if -100 <= cond <= 100 and row['winner'] == 'white':
            move = str(row['moves'])
            move = move.split()[0]
            list.append(move)

        elif -100 <= cond <= 100 and row['winner'] == 'black':
            move = str(row['moves'])
            move = move.split()[1]    ## error is from here
            list.append(move)


print(len(list))

Error

Traceback (most recent call last): 
  File "C:\Users\Said\Desktop\Шахматы\main.py", line 18, in <module> 
    move = move.split()[1] 
IndexError: list index out of range

CSV file: https://docs.google.com/spreadsheets/d/1HkVhU_DL22OquSbvuhKUhbWHMVNE2Qek9Q88mKGKs_4/edit#gid=230018563

CodePudding user response:

There is one of the moves that just have one movement, that is the reason, it fails in ['d3'] element, so add a condition to resolve that case

elif -100 <= cond <= 100 and row['winner'] == 'black':
    move = str(row['moves'])
    move = move.split()[1] # <- fails here because move = 'd3'
    list.append(move)
  • Related