Created
December 8, 2016 04:46
-
-
Save qwhex/791a0b1dfdf4ab1c48448453f0101aca to your computer and use it in GitHub Desktop.
Functional csv.DictWriter example where columns keep the original order
This file contains 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 python3 | |
# Functional csv.DictWriter example where columns keep the original order | |
import csv | |
def gen_rows(input_path): | |
with open(input_path) as input_file: | |
reader = csv.DictReader(input_file) | |
yield reader.fieldnames | |
for row in reader: | |
yield row | |
def put_rows(output_path, rows): | |
with open(output_path, 'w') as output_file: | |
field_names = next(rows) | |
writer = csv.DictWriter(output_file, fieldnames=field_names) | |
writer.writeheader() | |
for row in rows: | |
writer.writerow(row) | |
if __name__ == "__main__": | |
put_rows('output.csv', gen_rows('input.csv')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment