Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ jobs:
csvjoin < examples/dummy.csv
csvjson < examples/dummy.csv
csvlook < examples/dummy.csv
csvslice < examples/dummy.csv
csvsort < examples/dummy.csv
csvsql < examples/dummy.csv
csvstack < examples/dummy.csv
Expand All @@ -46,6 +47,7 @@ jobs:
printf 'a,b,c\n1,2,3' | csvjoin
printf 'a,b,c\n1,2,3' | csvjson
printf 'a,b,c\n1,2,3' | csvlook
printf 'a,b,c\n1,2,3' | csvslice
printf 'a,b,c\n1,2,3' | csvsort
printf 'a,b,c\n1,2,3' | csvsql
printf 'a,b,c\n1,2,3' | csvstack
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Unreleased
----------

- feat: Add :doc:`/scripts/csvslice` to select a range of data rows while preserving the header row.
- fix: :doc:`/scripts/csvgrep` treats an empty :code:`--regex` or :code:`--match` pattern as matching every value. Previously, with an empty pattern, :code:`--any-match` matched no rows, and :code:`--any-match --invert-match` matched every row.
- feat: :doc:`/scripts/csvcut` adds an :code:`--ignore-unknown-columns` option to skip identifiers in :code:`-c/--columns` that do not match a column in the input.
- feat: :doc:`/scripts/csvclean` adds a :code:`--remove-empty-columns` option to remove empty columns from standard output.
Expand Down
59 changes: 59 additions & 0 deletions csvkit/utilities/csvslice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#!/usr/bin/env python
import itertools
import sys

import agate

from csvkit.cli import CSVKitUtility, make_default_headers


class CSVSlice(CSVKitUtility):
description = 'Select a range of rows from a CSV file, preserving the header row.'
override_flags = ['L', 'I']

def add_arguments(self):
self.argparser.add_argument(
'-s', '--start-row', type=int, default=0,
help='The first data row to output, starting at 0. Defaults to the first row.')
self.argparser.add_argument(
'-n', '--num-rows', type=int,
help='The maximum number of data rows to output. Defaults to all remaining rows.')

def main(self):
if self.args.start_row < 0:
self.argparser.error('--start-row must be at least 0.')
if self.args.num_rows is not None and self.args.num_rows < 0:
self.argparser.error('--num-rows must be at least 0.')

if self.additional_input_expected():
sys.stderr.write('No input file or piped data provided. Waiting for standard input:\n')

rows = agate.csv.reader(self.skip_lines(), **self.reader_kwargs)
first_row = next(rows, None)
if first_row is None:
return

if self.args.no_header_row:
column_names = make_default_headers(len(first_row))
rows = itertools.chain([first_row], rows)
else:
column_names = first_row

writer = agate.csv.writer(self.output_file, **self.writer_kwargs)
writer.writerow(column_names)

if self.args.num_rows == 0:
return

start = self.args.start_row
stop = start + self.args.num_rows if self.args.num_rows is not None else None
writer.writerows(itertools.islice(rows, start, stop))


def launch_new_instance():
utility = CSVSlice()
utility.run()


if __name__ == '__main__':
launch_new_instance()
1 change: 1 addition & 0 deletions docs/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Processing
scripts/csvcut
scripts/csvgrep
scripts/csvjoin
scripts/csvslice
scripts/csvsort
scripts/csvstack

Expand Down
59 changes: 59 additions & 0 deletions docs/scripts/csvslice.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
========
csvslice
========

Description
===========

Select a range of rows from a CSV file, preserving the header row:

.. code-block:: none

csvslice [-s START_ROW] [-n NUM_ROWS] [FILE]

Arguments
=========

``-s START_ROW, --start-row START_ROW``
The first data row to output, starting at 0. Defaults to the first row.

``-n NUM_ROWS, --num-rows NUM_ROWS``
The maximum number of data rows to output. Defaults to all remaining rows.
A value of 0 outputs only the header.

See also: :doc:`../common_arguments`.

The header is not counted as a data row. Row numbers refer to CSV records,
so a quoted field containing line breaks is part of a single row. Values are
preserved without type inference. With ``--no-header-row``, default column names
are generated and the first input row is treated as data.

``--skip-lines`` skips physical lines before the input header, as in other tools.
``--zero`` applies to column numbers and does not change ``--start-row``.
``--linenumbers`` numbers the output data rows starting at 1.

The input is streamed: only rows up to the end of the requested slice are read.
The output is written to standard output, so it can be piped to another command
or redirected to a file. Empty input produces no output. A slice starting after
the last data row produces only the header.

Examples
========

Output the first ten data rows, with their header:

.. code-block:: bash

csvslice -n 10 examples/realdata/FY09_EDU_Recipients_by_State.csv

Output ten data rows, starting at zero-based row 10:

.. code-block:: bash

csvslice -s 10 -n 10 examples/realdata/FY09_EDU_Recipients_by_State.csv

Skip the first ten data rows and output the rest:

.. code-block:: bash

csvslice -s 10 examples/realdata/FY09_EDU_Recipients_by_State.csv
106 changes: 106 additions & 0 deletions man/csvslice.1
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
.\" Man page generated from reStructuredText
.\" by the Docutils 0.22.4 manpage writer.
.
.
.nr rst2man-indent-level 0
.
.de1 rstReportMargin
\\$1 \\n[an-margin]
level \\n[rst2man-indent-level]
level margin: \\n[rst2man-indent\\n[rst2man-indent-level]]
-
\\n[rst2man-indent0]
\\n[rst2man-indent1]
\\n[rst2man-indent2]
..
.de1 INDENT
.\" .rstReportMargin pre:
. RS \\$1
. nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin]
. nr rst2man-indent-level +1
.\" .rstReportMargin post:
..
.de UNINDENT
. RE
.\" indent \\n[an-margin]
.\" old: \\n[rst2man-indent\\n[rst2man-indent-level]]
.nr rst2man-indent-level -1
.\" new: \\n[rst2man-indent\\n[rst2man-indent-level]]
.in \\n[rst2man-indent\\n[rst2man-indent-level]]u
..
.TH "CSVSLICE" "1" "Nov 29, 2026" "2.2.0" "csvkit"
.SH NAME
csvslice \- csvslice Documentation
.SH DESCRIPTION
.sp
Select a range of rows from a CSV file, preserving the header row:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
csvslice [\-s START_ROW] [\-n NUM_ROWS] [FILE]
.EE
.UNINDENT
.UNINDENT
.SH ARGUMENTS
.INDENT 0.0
.TP
.B \fB\-s START_ROW, \-\-start\-row START_ROW\fP
The first data row to output, starting at 0. Defaults to the first row.
.TP
.B \fB\-n NUM_ROWS, \-\-num\-rows NUM_ROWS\fP
The maximum number of data rows to output. Defaults to all remaining rows.
A value of 0 outputs only the header.
.UNINDENT
.sp
See also: Arguments common to all tools \%<>\&.
.sp
The header is not counted as a data row. Row numbers refer to CSV records,
so a quoted field containing line breaks is part of a single row. Values are
preserved without type inference. With \fB\-\-no\-header\-row\fP, default column names
are generated and the first input row is treated as data.
.sp
\fB\-\-skip\-lines\fP skips physical lines before the input header, as in other tools.
\fB\-\-zero\fP applies to column numbers and does not change \fB\-\-start\-row\fP\&.
\fB\-\-linenumbers\fP numbers the output data rows starting at 1.
.sp
The input is streamed: only rows up to the end of the requested slice are read.
The output is written to standard output, so it can be piped to another command
or redirected to a file. Empty input produces no output. A slice starting after
the last data row produces only the header.
.SH EXAMPLES
.sp
Output the first ten data rows, with their header:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
csvslice \-n 10 examples/realdata/FY09_EDU_Recipients_by_State.csv
.EE
.UNINDENT
.UNINDENT
.sp
Output ten data rows, starting at zero\-based row 10:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
csvslice \-s 10 \-n 10 examples/realdata/FY09_EDU_Recipients_by_State.csv
.EE
.UNINDENT
.UNINDENT
.sp
Skip the first ten data rows and output the rest:
.INDENT 0.0
.INDENT 3.5
.sp
.EX
csvslice \-s 10 examples/realdata/FY09_EDU_Recipients_by_State.csv
.EE
.UNINDENT
.UNINDENT
.SH Author
Christopher Groskopf and contributors
.SH Copyright
2016, Christopher Groskopf and James McKinney
.\" End of generated man page.
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ csvjoin = "csvkit.utilities.csvjoin:launch_new_instance"
csvjson = "csvkit.utilities.csvjson:launch_new_instance"
csvlook = "csvkit.utilities.csvlook:launch_new_instance"
csvpy = "csvkit.utilities.csvpy:launch_new_instance"
csvslice = "csvkit.utilities.csvslice:launch_new_instance"
csvsort = "csvkit.utilities.csvsort:launch_new_instance"
csvsql = "csvkit.utilities.csvsql:launch_new_instance"
csvstack = "csvkit.utilities.csvstack:launch_new_instance"
Expand All @@ -81,6 +82,7 @@ exclude = ["tests", "tests.*"]
"man/csvjson.1",
"man/csvlook.1",
"man/csvpy.1",
"man/csvslice.1",
"man/csvsort.1",
"man/csvsql.1",
"man/csvstack.1",
Expand Down
120 changes: 120 additions & 0 deletions tests/test_utilities/test_csvslice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import io
import sys
from unittest.mock import patch

from csvkit.utilities.csvslice import CSVSlice, launch_new_instance
from tests.utils import CSVKitTestCase, EmptyFileTests, stdin_as_string


class TestCSVSlice(CSVKitTestCase, EmptyFileTests):
Utility = CSVSlice

def test_launch_new_instance(self):
with patch.object(sys, 'argv', ['csvslice', 'examples/dummy.csv']):
launch_new_instance()

def test_default(self):
self.assertRows(['examples/test_utf8.csv'], [
['foo', 'bar', 'baz'],
['1', '2', '3'],
['4', '5', 'ʤ'],
])

def test_head(self):
self.assertRows(['-n', '1', 'examples/test_utf8.csv'], [
['foo', 'bar', 'baz'],
['1', '2', '3'],
])

def test_slice(self):
self.assertRows(['-s', '1', '-n', '1', 'examples/test_utf8.csv'], [
['foo', 'bar', 'baz'],
['4', '5', 'ʤ'],
])

def test_start_without_limit(self):
self.assertRows(['--start-row', '1', 'examples/test_utf8.csv'], [
['foo', 'bar', 'baz'],
['4', '5', 'ʤ'],
])

def test_zero_rows(self):
self.assertRows(['--num-rows', '0', 'examples/dummy.csv'], [['a', 'b', 'c']])

def test_start_after_end(self):
self.assertRows(['-s', '10', 'examples/dummy.csv'], [['a', 'b', 'c']])

def test_limit_after_end(self):
self.assertRows(['-n', '10', 'examples/dummy.csv'], [
['a', 'b', 'c'],
['1', '2', '3'],
])

def test_no_header_row(self):
self.assertRows(['-H', '-s', '1', '-n', '1', 'examples/test_utf8.csv'], [
['a', 'b', 'c'],
['1', '2', '3'],
])

def test_skip_lines(self):
self.assertRows(['-K', '3', '-n', '1', 'examples/test_skip_lines.csv'], [
['a', 'b', 'c'],
['1', '2', '3'],
])

def test_linenumbers(self):
self.assertRows(['-l', '-s', '1', 'examples/test_utf8.csv'], [
['line_number', 'foo', 'bar', 'baz'],
['1', '4', '5', 'ʤ'],
])

def test_compressed(self):
self.assertRows(['-n', '1', 'examples/dummy.csv.gz'], [
['a', 'b', 'c'],
['1', '2', '3'],
])

def test_stdin_with_multiline_fields(self):
data = b'id;value\n001;"two\nlines"\n002;null\n003;last\n'
with stdin_as_string(io.BytesIO(data)):
self.assertRows(['-d', ';', '-s', '1', '-n', '1'], [
['id', 'value'],
['002', 'null'],
])

def test_zero_start_and_preserve_values(self):
data = b'id,value\n001,"two\nlines"\n002,null\n'
with stdin_as_string(io.BytesIO(data)):
self.assertRows(['--zero', '-s', '0', '-n', '1', '-'], [
['id', 'value'],
['001', 'two\nlines'],
])

def test_header_only(self):
with stdin_as_string(io.BytesIO(b'a,b\n')):
self.assertRows(['-n', '1'], [['a', 'b']])

def test_empty_no_header_row(self):
with stdin_as_string(io.BytesIO(b'')):
self.assertRows(['-H'], [])

def test_stops_reading_at_limit(self):
class LimitedInput(io.StringIO):
def __next__(self):
if self.tell() == len('a\n1\n'):
raise AssertionError('Read beyond the requested slice')
return super().__next__()

with patch.object(CSVSlice, '_open_input_file', return_value=LimitedInput('a\n1\n2\n')):
self.assertRows(['-n', '1'], [['a'], ['1']])

with patch.object(CSVSlice, '_open_input_file', return_value=LimitedInput('a\n1\n2\n')):
self.assertRows(['-s', '10', '-n', '0'], [['a']])

def test_invalid_start(self):
for value in ['-1', '-2']:
with self.subTest(value=value):
self.assertError(launch_new_instance, ['-s', value], '--start-row must be at least 0.')

def test_invalid_count(self):
self.assertError(launch_new_instance, ['-n', '-1'], '--num-rows must be at least 0.')