Richard Richard - 1 year ago 139
Python Question

Python - Print list of CSV strings in aligned columns

I have written a Python 2/3 compatible script that parses data and builds the output as a list of CSV strings. The script provides an option to write the data to a CSV file, or display to stdout. While I could easily iterate through the list and replace "," with "\t" when displaying to stdout, the items are of arbitrary length, and thusly don't line up in a nice format due to variances in tabs. I have done quite a bit of research, and believe that string format options may accomplish what I'm after. That said, I can't seem to find an example that helps me get the syntax correct.

I would prefer not to use an external library. I am aware that there are many options available if I went that route, but I want the script to be as compatible and simple as possible.

Here is an example:

Any suggestions are much appreciated.

Answer Source
import csv
from StringIO import StringIO

rows = list(csv.reader(StringIO(

widths = [max(len(row[i]) for row in rows) for i in range(len(rows[0]))]

for row in rows:
    print(' | '.join(cell.ljust(width) for cell, width in zip(row, widths)))


value1 | somevalue2 | value3           | reallylongvalue4 | value5 | superlongvalue6
value1 | value2     | reallylongvalue3 | value4           | value5 | somevalue6     
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download