简体   繁体   English

Python的csv.reader(filename)真的会返回一个列表吗? 似乎不是这样

[英]Does Python's csv.reader(filename) REALLY return a list? Doesn't seem so

So I am still learning Python and I am on learning about reading files, csv files today. 所以我还在学习Python,我正在学习如何阅读文件,csv文件。 The lesson I just watched tells me that using 我刚看过的课程告诉我使用

csv.reader(filename)

returns a list. 返回一个列表。

So I wrote the following code: 所以我写了下面的代码:

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

and what it prints is 它打印的是什么

<_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]

What you get is an iterable , ie 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: 您可以将它传递给for循环,或使用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 eg throw it out of memory again before reading the next. 使用可迭代,您可以选择一次查看一个元素,例如在读取下一个元素之前再次将其丢弃。

The return value of the csv.reader is an iterator (reader object). csv.reader的返回值是迭代器(reader对象)。

You need to iterate it, to get lists: 你需要迭代它,以获得列表:

import csv
my_file = open(file_name.csv, mode='r')
parsed_data = csv.reader(my_file)
for row in parsed_data:
    print(row)   # <--- a list of strings

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM