12

I have a test.csv file:

foo,bar,foobar,barfoo

1,2,3,4
5,6,7,8
9,10,11,12

And the following CSV parser:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import json

f = open ( 'test.csv', 'r' )

reader = csv.DictReader( f, fieldnames = ( "foo","bar","foobar","barfoo" ))

out = json.dumps( [ row for row in reader ], ensure_ascii=False, encoding="utf-8")

print out

Is there an easy way to replace the fieldnames in the output, without changing the header of the CSV file?

My current output is this:

[
   {
      "foobar":"foobar",
      "foo":"foo",
      "bar":"bar",
      "barfoo":"barfoo"
   },
   {
      "foobar":"3",
      "foo":"1",
      "bar":"2",
      "barfoo":"4"
   },
   {
      "foobar":"7",
      "foo":"5",
      "bar":"6",
      "barfoo":"8"
   },
   {
      "foobar":"11",
      "foo":"9",
      "bar":"10",
      "barfoo":"12"
   }
]

Could I get something like this:

[
   {
      "id":"foobar",
      "email":"foo",
      "name":"bar",
      "phone":"barfoo"
   },
   {
      "id":"3",
      "email":"1",
      "name":"2",
      "phone":"4"
   },
   {
      "id":"7",
      "email":"5",
      "name":"6",
      "phone":"8"
   },
   {
      "id":"11",
      "email":"9",
      "name":"10",
      "phone":"12"
   }
]
dreftymac
  • 31,404
  • 26
  • 119
  • 182
cherrun
  • 2,102
  • 8
  • 34
  • 51

2 Answers2

17

The easiest way is to just set:

reader.fieldnames = "email", "name", "id",  "phone"

You can save the old fieldnames if you want too.

jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 1
    Oh. So the `fieldnames` don't have to correspond with the actual `fieldnames` of the header line in the `CSV`? – cherrun Jun 11 '13 at 08:42
  • 1
    @cherrun No they don't. On a side note, You don't even need to specify them like you did. `csv.DictReader(f)` will read the first line as the header by default, without need for `fieldnames=...` but maybe it's better the way you have it – jamylak Jun 11 '13 at 09:26
10

Just replace this line:

reader = csv.DictReader(f, fieldnames = ( "foo","bar","foobar","barfoo" ))

with this:

reader = csv.DictReader(f, fieldnames=("id", "email", "name", "phone"))
Oleksandr Fedorov
  • 1,213
  • 10
  • 17
  • 1
    Note that the fieldnames argument provides a header for your data. If the argument is omitted, it will be taken from the first row of your csv file. – Oleksandr Fedorov Jun 11 '13 at 08:45