Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import csv
import json
csvfile = open('test.csv', 'r')
jsonfile = open('file.json', 'w')
def lookahead(iterable):
"""Pass through all values from the given iterable, augmented by the
information if there are more values to come after the current one
(True), or if it is the last value (False).
"""
# Get an iterator and pull the first value.
it = iter(iterable)
last = next(it)
# Run the iterator to exhaustion (starting from the second value).
for val in it:
# Report the *previous* value (more to come).
yield last, True
last = val
# Report the last value.
yield last, False
fieldnames = ("country","code","format","length")
reader = csv.DictReader( csvfile, fieldnames)
jsonfile.write('{\"values\":[')
for row, hasMore in lookahead(reader):
json.dump(row, jsonfile)
if hasMore:
jsonfile.write(',\n')
else :
jsonfile.write('\n')
jsonfile.write(']}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment