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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With