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

Question:

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:UsersSaidDesktopШахматы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

Asked By: Just_a_Goose

||

Answers:

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)
Answered By: Matías Rivas
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.