微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python file.csv 在列表中读取和转换

如何解决Python file.csv 在列表中读取和转换

只是好奇,我是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) 会产生一个空列表。如果你想多次遍历文件,先把它转换成一个列表,然后你就可以重复使用这个列表了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。