2

I'm doing some basic CSV files manipulation when I stumbled upon this problem, now I know how to avoid it but I just want to have a better understanding of what is going on. Whenever I want to iterate the csv.reader object, I can do so easily. However, whenever I try to turn the object into a list via another variable, it blocks the iterative loop that iterates the csv.reader object from starting.

def checkPlayer(discordName, playerName):
    with open ('PLAYERS.csv', 'r') as fil:
        r = csv.reader(fil)
        l = list(r)
        lineNum = 1 
        for line in r:
            print(line)

The l = list(r) is what blocks the loop from executing.

The code below works fine, and the loop executes normally.

def checkPlayer(discordName, playerName):
    with open ('PLAYERS.csv', 'r') as fil:
        r = csv.reader(fil)
        lineNum = 1 
        for line in r:
            print(line)

I'm expecting the reason on why this happens is because when turning the csv.reader to a list, an iteration of the object happens which means that it sets the csv.reader object at the endpoint before executing the loop.

kalehmann
  • 4,821
  • 6
  • 26
  • 36
S.Riyadh
  • 23
  • 2

1 Answers1

2

The csv.reader represents the underlying file (only adding some structure of CSV on top of the raw file). Therefore, it can be read once, from the beginning to the end and it does not return anything once you reach the end of the file.

When you run l = list(r) you read the whole contents of the file represented by handle r and reach the end of the underlying file. Therefore, any further iteration over the handle (for line in r:) will start at the end of the file and therefore you will read nothing.

To fix this you can rewind the file to the beginning: fil.seek(0) before reading from the file for the second time:

with open ('PLAYERS.csv', 'r') as fil:
        r = csv.reader(fil)
        l = list(r)
        lineNum = 1 
        fil.seek(0)
        for line in r:
            print(line)
sophros
  • 14,672
  • 11
  • 46
  • 75