Skip to content

Instantly share code, notes, and snippets.

@JoeGermuska
Created September 14, 2009 17:56
Show Gist options
  • Save JoeGermuska/186804 to your computer and use it in GitHub Desktop.
Save JoeGermuska/186804 to your computer and use it in GitHub Desktop.
Like cut, but smart about CSV quoting
#!/usr/bin/env python
"""
Like cut, but for CSVs. To be used from a shell command line.
Change row[1] to the row index to be printed. row[1] will print the second
item in the row.
Note that fields are zero-based, as opposed to 'cut' where they are 1-based.
Leveraged from/motivated by an example from @bycoffe
Usage:
csvcut foobar.csv
(prints the first column of each row of foobar.csv)
head -10 foobar.csv | csvcut -f 0,2
(prints the first and third columns of the first ten lines of foobar.csv)
"""
import sys, csv, getopt
opts, args = getopt.getopt(sys.argv[1:], "f:", ["fields="])
if args:
i = open(args[0])
else:
i = sys.stdin
if opts:
cols = opts[0][1].split(",")
else:
cols = [0]
for row in csv.reader(i):
for c in cols:
print row[int(c)],
print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment