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

Add option to truncate long columns with an additional option for csvlook (fixes #389) #482

Closed
wants to merge 2 commits into from
Closed
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
15 changes: 12 additions & 3 deletions csvkit/utilities/csvlook.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ class CSVLook(CSVKitUtility):
description = 'Render a CSV file in the console as a fixed-width table.'

def add_arguments(self):
pass
self.argparser.add_argument('-c', '--cutoff', type=int, dest='cutoff',
help='Cut off all columns after this number of characters. Intended to improve readability for CSV files with very long text in columns.')

def main(self):
rows = CSVKitReader(self.input_file, **self.reader_kwargs)
Expand Down Expand Up @@ -48,9 +49,15 @@ def main(self):
for i, v in enumerate(row):
try:
if len(v) > widths[i]:
widths[i] = len(v)
if self.args.cutoff:
widths[i] = min(len(v), self.args.cutoff)
else:
widths[i] = len(v)
except IndexError:
widths.append(len(v))
if self.args.cutoff:
widths.append(min(len(v), self.args.cutoff))
else:
widths.append(len(v))

# Dashes span each width with '+' character at intersection of
# horizontal and vertical dividers.
Expand All @@ -64,6 +71,8 @@ def main(self):
for j, d in enumerate(row):
if d is None:
d = ''
if self.args.cutoff:
d = d[0:self.args.cutoff]
output.append(' %s ' % six.text_type(d).ljust(widths[j]))

self.output_file.write('| %s |\n' % ('|'.join(output)))
Expand Down