Skip to content

Instantly share code, notes, and snippets.

@eponvert eponvert/csvcut
Created Feb 28, 2014

Embed
What would you like to do?
Like cut for CSVs and TSVs and what not
#!/usr/bin/env python2.7
# Copyright (c) 2014 Elias Ponvert
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from argparse import ArgumentParser
from csv import reader as csv_reader, writer as csv_writer
import re
__author__ = "Elias Ponvert"
__copyright__ = "Copyright 2014, Elias Ponvert"
__version__ = 'v1.0.2'
__license__ = "MIT"
def csvcut(fh_in, fh_out, slices, input_delim, output_delim, skip_header=False):
"""Transform CSV input
Parses fields out of each line of the input stream, writes a subset of the
fields to the output stream
Args:
fh_in: Input file stream
fh_out: Output file stream
slices: List of Python slice objects, to extract from the rows from the input
input_delim: The field separator for the input stream
output_delim: The field separator for the output stream
skip_header: If true, skip the first line of the input stream
Raises:
IOError: An error occured accessing the input stream or the output stream
"""
csv_in = csv_reader(fh_in, delimiter=input_delim)
if skip_header:
csv_in.next()
csv_out = csv_writer(fh_out, delimiter=output_delim)
for row in csv_in:
csv_out.writerow(sum([row[slice] for slice in slices], []))
def _mkslice(s):
s = s.strip()
m = re.match(r'^(\d+)$', s)
if m:
n = int(m.group(1))
return slice(n-1, n)
m = re.match(r'^(\d+)-(\d+)$', s)
if m:
return slice(int(m.group(1))-1, int(m.group(2)))
m = re.match(r'^-(\d+)$', s)
if m:
return slice(int(m.group(1)))
m = re.match(r'^(\d+)-$', s)
if m:
return slice(int(m.group(1))-1, None)
raise ValueError("Unexpected slice format: %s" % (s,))
def _parse_delim(s):
if s == '\\t':
return '\t'
else:
return s
def main(argv):
ap = ArgumentParser(description="Like cut, for CSVs and TSVs and what not")
ap.add_argument('--version', action='version', version='%(prog)s ' + __version__)
ap.add_argument('-f', '--fields', metavar='LIST', default='0-',
help="select only these fields; supported formats = comma-separated, N-M, N-, -M")
ap.add_argument('-d', '--delimiter', metavar='DELIM', default='\t',
help="use DELIM instead of TAB for field delimiter")
ap.add_argument('--output-delimiter', metavar='STRING', default=None,
help="use STRING as the output delimiter, the default is to use the input delimiter")
ap.add_argument('--skip-header', action='store_true', help="skip first row of input")
ap.add_argument('files', metavar='FILE', nargs='*', default=None, help="csv/tsv file input")
args = ap.parse_args(argv)
slices = map(_mkslice, args.fields.split(','))
input_delim = _parse_delim(args.delimiter)
output_delim = _parse_delim(args.output_delimiter) or input_delim
from sys import stdout
csvcut_args = [stdout, slices, input_delim, output_delim, args.skip_header]
try:
if args.files:
for f in args.files:
with open(f, 'rU') as f_in:
csvcut(f_in, *csvcut_args)
else:
from sys import stdin
csvcut(stdin, *csvcut_args)
except IOError, e:
if e.errno == 32: # Broken pipe
pass
else:
raise e
if __name__ == '__main__':
from sys import argv
main(argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.