Skip to content

Instantly share code, notes, and snippets.

@Supermathie
Created April 14, 2014 20:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Supermathie/10681756 to your computer and use it in GitHub Desktop.
Save Supermathie/10681756 to your computer and use it in GitHub Desktop.
python CSV example
#!/usr/bin/env python
import csv
import sys
from pprint import pprint
csvreader = csv.reader(sys.stdin)
# Read the header line and extract the column names
header = csvreader.next()
colindexes = {}
for col,name in enumerate(header):
colindexes[name] = col
results = []
for lineno, row in enumerate(csvreader):
colA = row[colindexes["Column A"]]
colB = row[colindexes["Column B"]]
colC = row[colindexes["Column C"]]
# Massage the data in some way
colD = (int(colA) + int(colB)) * int(colC)
results.append([colA, colB, colC, colD])
# Print the resulting file to stdout
csvwriter = csv.writer(sys.stdout)
# Write the header row
csvwriter.writerow(["Column A", "Column B", "Column C", "Column D"])
for line in results:
csvwriter.writerow(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment