CSV Dictionary
JC
chalao.adda at gmail.com
Mon Dec 29 11:11:36 EST 2014
On Mon, 29 Dec 2014 09:47:23 -0600, Skip Montanaro wrote:
> On Mon, Dec 29, 2014 at 9:35 AM, JC <chalao.adda at gmail.com> wrote:
>> How could I get the all the records?
>
> This should work:
>
> with open('x.csv','rb') as f:
> rdr = csv.DictReader(f,delimiter=',')
> rows = list(rdr)
>
> You will be left with a list of dictionaries, one dict per row, keyed by
> the values in the first row:
>
>>>> import csv with open('x.csv','rb') as f:
> ... rdr = csv.DictReader(f,delimiter=',')
> ... rows = list(rdr)
> ...
>>>> import pprint pprint.pprint(rows)
> [{'id': '1', 'name': 'ABC', 'password': '1234', 'userid': 'def at ghi'},
> {'id': '2', 'name': 'DEF', 'password': 'asdf', 'userid': 'ghi at jkl'},
> {'id': '3', 'name': 'GHI', 'password': 'zxcv', 'userid': 'jkl at mno'}]
>
> Skip
Thanks. That did the job.
But now I see another problem. I cannot use the "rdr" object anymore. For
example, I wanted to count the number of records. I used -
count = sum(1 for r in rdr)
It returned 0 records.
Do I have to open the file again to get 'rdr' work again?
Thanks again.
More information about the Python-list
mailing list