Skip to content

Commit

Permalink
csvformat: Add a --skip-header option, closes #929
Browse files Browse the repository at this point in the history
  • Loading branch information
jpmckinney committed Oct 17, 2023
1 parent edf0de7 commit f91faa4
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
@@ -1,6 +1,7 @@
Unreleased
----------

* :doc:`/scripts/csvformat` adds a :code:`--skip-header` option to not output a header row.
* :doc:`/scripts/csvstat` adds a :code:`--json` option to output results as JSON text.
* :doc:`/scripts/csvstat` adds an :code:`--indent` option to indent the JSON text when :code:`--json` is set.
* :doc:`/scripts/csvstat` reports a "Non-null values" statistic (or a :code:`nonnulls` column when :code:`--csv` is set).
Expand Down
9 changes: 7 additions & 2 deletions csvkit/utilities/csvformat.py
Expand Up @@ -12,6 +12,9 @@ class CSVFormat(CSVKitUtility):
override_flags = ['L', 'blanks', 'date-format', 'datetime-format']

def add_arguments(self):
self.argparser.add_argument(
'--skip-header', dest='skip_header', action='store_true',
help='Do not output a header row.')
self.argparser.add_argument(
'-D', '--out-delimiter', dest='out_delimiter',
help='Delimiting character of the output CSV file.')
Expand Down Expand Up @@ -63,9 +66,11 @@ def main(self):
if self.args.no_header_row:
# Peek at a row to get the number of columns.
_row = next(reader)
reader = itertools.chain([_row], reader)
headers = make_default_headers(len(_row))
writer.writerow(headers)
reader = itertools.chain([headers, _row], reader)

if self.args.skip_header:
next(reader)

writer.writerows(reader)

Expand Down
1 change: 1 addition & 0 deletions docs/scripts/csvformat.rst
Expand Up @@ -24,6 +24,7 @@ Convert a CSV file to a custom output format.:
optional arguments:
-h, --help show this help message and exit
--skip-header Do not output a header row.
-D OUT_DELIMITER, --out-delimiter OUT_DELIMITER
Delimiting character of the output CSV file.
-T, --out-tabs Specify that the output CSV file is delimited with
Expand Down
10 changes: 10 additions & 0 deletions tests/test_utilities/test_csvformat.py
Expand Up @@ -19,6 +19,16 @@ def test_skip_lines(self):
'1|2|3',
])

def test_skip_header(self):
self.assertLines(['--skip-header', 'examples/dummy.csv'], [
'1,2,3',
])

def test_skip_header_no_header_row(self):
self.assertLines(['--no-header-row', '--skip-header', 'examples/no_header_row.csv'], [
'1,2,3',
])

def test_no_header_row(self):
self.assertLines(['--no-header-row', 'examples/no_header_row.csv'], [
'a,b,c',
Expand Down

0 comments on commit f91faa4

Please sign in to comment.