Question on the "csv" library

Benjamin Kaplan benjamin.kaplan at case.edu
Thu Aug 27 15:29:15 EDT 2009


On Thu, Aug 27, 2009 at 3:06 PM, vsoler <vicente.soler at gmail.com> wrote:
>
> I am trying to read a csv file generated by excel.
>
> Although I succeed in reading the file, the format that I get is not
> suitable for me.
>
> I've done:
>
> >>> import csv
> >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'))
>
> >>> print spamReader
> <_csv.reader object at 0x01022E70>
>
> >>> for row in spamReader:
>        print row
>
>
> ['codigo;nombre;cantidad']
> ['a;qwe;1']
> ['b;asd;2']
> ['c;zxc;3']
>
> My questions are:
>
> 1- Why using "print spamReader" I cannot see the data?
>    I expected to see a list of lists, a kind of a matrix, but I get
> nothing

It's because csv.reader does the same thing open does. It returns an
iterable, not a list. The file is opened but not processed until you
iterate through it. You cannot see the data when you do print
spamReader because of this and because the csv reader object does
define a __str__ method.

>
> 2- Why are the rows in a single string?
>   I expected a list of fields that, when text, would be delimited by
> "
>  To tell the truth, the file generated by excel does not contain the
> strings delimited by ". Isn't it weird?

CSV stands for comma separated variables. It actually has nothing to
do with the quotes- they're just used in case an element has a comma
in it, so the reader knows it's a string literal and not a separate
column. Your comma separated variable worksheet seems to be semicolon
separated. That's why the reader isn't splitting it.

>
> 3- Is there anything I can do to have my data in a list of lists
> structure? would another kind of data suit better my needs?
>
just do a list comprehension
sheet = [row for row in spamReader]


> Thank you for your help
>
> Vicente Soler
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list