Skip to content

Instantly share code, notes, and snippets.

@qwhex
Created December 8, 2016 04:46
Show Gist options
  • Save qwhex/791a0b1dfdf4ab1c48448453f0101aca to your computer and use it in GitHub Desktop.
Save qwhex/791a0b1dfdf4ab1c48448453f0101aca to your computer and use it in GitHub Desktop.
Functional csv.DictWriter example where columns keep the original order
#!/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