Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added 'column numbers everywhere' to csvcut #1209

Closed
wants to merge 7 commits into from
Closed
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
16 changes: 14 additions & 2 deletions csvkit/utilities/csvcut.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ def add_arguments(self):
self.argparser.add_argument(
'-x', '--delete-empty-rows', dest='delete_empty', action='store_true',
help='After cutting, delete rows which are completely empty.')
self.argparser.add_argument(
'-N', '--column-numbers', dest='number_columns_everywhere', action='store_true',
help='Add column numbering everywhere, in header and cells.')

def main(self):
if self.args.names_only:
Expand All @@ -47,10 +50,19 @@ def main(self):
rows, column_names, column_ids = self.get_rows_and_column_names_and_column_ids(**self.reader_kwargs)

output = agate.csv.writer(self.output_file, **self.writer_kwargs)
output.writerow([column_names[column_id] for column_id in column_ids])

one_or_zero = 0 if self.args.zero_based else 1
if self.args.number_columns_everywhere:
output.writerow([f'{column_id + one_or_zero}~{column_names[column_id]}' for column_id in column_ids])
else:
output.writerow([column_names[column_id] for column_id in column_ids])

for row in rows:
out_row = [row[column_id] if column_id < len(row) else None for column_id in column_ids]
if self.args.number_columns_everywhere:
out_row = [f'{column_id + one_or_zero}~{row[column_id]}'
if column_id < len(row) else None for column_id in column_ids]
else:
out_row = [row[column_id] if column_id < len(row) else None for column_id in column_ids]

if not self.args.delete_empty or any(out_row):
output.writerow(out_row)
Expand Down
6 changes: 6 additions & 0 deletions tests/test_utilities/test_csvcut.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ def test_simple(self):
['1', '3'],
])

def test_column_numbers(self):
self.assertRows(['-c', '1,3', '-N', 'examples/dummy.csv'], [
['1~a', '3~c'],
['1~1', '3~3'],
])

def test_linenumbers(self):
self.assertRows(['-c', '1,3', '-l', 'examples/dummy.csv'], [
['line_number', 'a', 'c'],
Expand Down