Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

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]
like image 590
Sindyr Avatar asked Dec 14 '15 00:12

Sindyr


1 Answers

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.

like image 135
Aasmund Eldhuset Avatar answered Nov 14 '22 23:11

Aasmund Eldhuset