问题描述
只是好奇,我是python初学者。我来自巴西。如果我执行我的代码,在这一步 reader_list = list (reader)
不起作用,不要在列表中转换文件。如果我评论“for”块,没关系,它是列表中的转换 var reader
。我想知道如果打开文件并操作它,需要再次打开,因为如果我在另一个var中再次打开并重复步骤,它可以正常工作。
这是我的代码:
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()
输出:
>>> %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','1.73']
['Tiago','1.74']
['Tiago','1.75']
['Tiago','1.76']
['Tiago','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
>>>
好的,如果评论“for row in reader: print(row)”:
>>> %run file_exemplo_pros_mano.py
<_csv.reader object at 0x041B5870>
<class '_csv.reader'>
==================
Keys: ['Nome','Altura']
Row 1: ['Tiago','1.72']
Row 2: ['Tiago','1.73']
>>>
解决方法
cvs.reader
返回一个迭代器。在 for
循环中使用完所有行后,迭代器将耗尽。它在最后。因此,调用 list(reader)
会产生一个空列表。如果你想多次遍历文件,先把它转换成一个列表,然后你就可以重复使用这个列表了。