Search code examples
pythonlistcsvreader

Python file.csv read and transform in list


it's just a curiosity, I'm a python beginner. I'm from Brasil. If I execute my code, in this step reader_list = list (reader) not work, don not transform file in list. If I comment "for" block, it's okay, it's transform var reader in list. I want to know if open file and operate it, it's necessary open again, because if I open again in another var and repeat steps, It's work okay.

Here is my code:

import csv

file = open("planilha.csv", "r")
reader = csv.reader(file)

print(reader)
print(type(reader))

for row in reader:
    print(row)   

print("\n==================", end="\n\n")

reader_list = list(reader)
print("Keys:\t", reader_list[0])
print("Row 1:\t", reader_list[1])
print("Row 2:\t", reader_list[2])

file.close()

The output:

>>> %Run file_exemplo_pros_mano.py
>>> %Run file_exemplo_pros_mano.py
<_csv.reader object at 0x03D06870>
<class '_csv.reader'>
['Nome', 'Sobrenome', 'Sexo', 'Idade', 'Altura']
['Tiago', 'San Martin', 'Masculino', '34', '1.72']
['Tiago', 'San Martin', 'Masculino', '34', '1.73']
['Tiago', 'San Martin', 'Masculino', '34', '1.74']
['Tiago', 'San Martin', 'Masculino', '34', '1.75']
['Tiago', 'San Martin', 'Masculino', '34', '1.76']
['Tiago', 'San Martin', 'Masculino', '34', '1.77']

==================

Traceback (most recent call last):
  File "C:\Users\tiago.martin\Documents\LetsCode_Python\file_exemplo_pros_mano.py", line 17, in <module>
    print("Keys:\t", reader_list[0])
IndexError: list index out of range
>>> 

Ok, if comment the "for row in reader: print(row)":

>>> %Run file_exemplo_pros_mano.py
<_csv.reader object at 0x041B5870>
<class '_csv.reader'>

==================

Keys:    ['Nome', 'Sobrenome', 'Sexo', 'Idade', 'Altura']
Row 1:   ['Tiago', 'San Martin', 'Masculino', '34', '1.72']
Row 2:   ['Tiago', 'San Martin', 'Masculino', '34', '1.73']
>>> 

Solution

  • cvs.reader returns an iterator. After you consume all the rows in the for loop, the iterator is exhausted. It is at the end. So, calling list(reader) produces an empty list. If you want to run through the file several times, convert it to a list FIRST, and then you can consume the list repeatedly.