Python的csv.reader(filename)是否真的返回列表?好像不是 [英] Does Python's csv.reader(filename) REALLY return a list? Doesn't seem so

查看:33
本文介绍了Python的csv.reader(filename)是否真的返回列表?好像不是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我仍在学习Python,并且现在正在学习有关读取文件,csv文件的知识.我刚刚看过的课程告诉我,使用

So I am still learning Python and I am on learning about reading files, csv files today. The lesson I just watched tells me that using

csv.reader(filename)

返回列表.

所以我写了以下代码:

import csv
my_file = open(file_name.csv, mode='r')
parsed_data = csv.reader(my_file)
print(parsed_data)

及其打印的是

<_csv.reader object at 0x0000000002838118>

如果输出的是列表,我是否应该获取列表,即类似这样的东西?

If what it outputs is a list, shouldn't I be getting a list, ie, something like this?

[value1, value2, value3]

推荐答案

您得到的是一个 可迭代的 ,即将为您提供一系列其他对象(在这种情况下为字符串)的对象.您可以将其传递到for循环,或使用list()获取实际列表:

What you get is an iterable, i.e. an object which will give you a sequence of other objects (in this case, strings). You can pass it to a for loop, or use list() to get an actual list:

parsed_data = list(csv.reader(my_file))

以这种方式设计的原因是,它允许您处理大于计算机上的内存量的文件(或者仅处理那些足以占用不便的内存的文件).将其所有内容加载到列表中).有了迭代,您可以选择一次查看一个元素,例如在读取下一个之前,再次将其扔出内存.

The reason it is designed this way is that it allows you to work with files that are larger than the amount of memory you have on your computer (or simply files that are large enough to consume inconvenient amounts of memory if you were to load all of its contents into a list). With an iterable, you may choose to look at one element at a time and e.g. throw it out of memory again before reading the next.

这篇关于Python的csv.reader(filename)是否真的返回列表?好像不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆