Skip to content

Instantly share code, notes, and snippets.

@j2labs
Created June 29, 2013 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j2labs/5892509 to your computer and use it in GitHub Desktop.
Save j2labs/5892509 to your computer and use it in GitHub Desktop.
Basic example of using Python's csv module
#!/usr/bin/env python
# Try putting this data in a file called 'band.csv'
# James,Dennis,Drums,punk
# Rob,Spectre,Guitar,punk
import csv
import json
filename = 'basic.csv'
def read_file():
f = open(filename, 'r')
for line in f:
print line
f.close()
def read_as_csv():
csv_data = []
f = open(filename, 'r')
csv_file = csv.reader(f)
for row in csv_file:
csv_data.append(row)
f.close()
return csv_data
def csv_to_json(csv_data):
json_data = []
for row in csv_data:
### Create dict for row
json_dict = {}
json_dict['first'] = row[0]
json_dict['last'] = row[1]
json_dict['role'] = row[2]
json_dict['genre'] = row[3]
### Add to json_data
json_data.append(json_dict)
json_string = json.dumps(json_data)
return json_string
### Example use
csv_data = read_as_csv()
json_data = csv_to_json(csv_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment