Created
June 29, 2013 20:18
-
-
Save j2labs/5892509 to your computer and use it in GitHub Desktop.
Basic example of using Python's csv module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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