Last active
July 9, 2016 16:27
-
-
Save azakordonets/cbb913cd41f65194b3ea8453322bfae4 to your computer and use it in GitHub Desktop.
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
| 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