Python - Print list of CSV strings in aligned columns

瘦欲@ 提交于 2019-12-01 09:31:58
import csv
from StringIO import StringIO

rows = list(csv.reader(StringIO(
    '''value1,somevalue2,value3,reallylongvalue4,value5,superlongvalue6
value1,value2,reallylongvalue3,value4,value5,somevalue6''')))

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)))

Output:

value1 | somevalue2 | value3           | reallylongvalue4 | value5 | superlongvalue6
value1 | value2     | reallylongvalue3 | value4           | value5 | somevalue6     
def printCsvStringListAsTable(csvStrings):

    # convert to list of lists
    csvStrings = map(lambda x: x.split(','), csvStrings)

    # get max column widths for printing
    widths = []
    for idx in range(len(csvStrings[0])):
        columns = map(lambda x: x[idx], csvStrings)
        widths.append(
            len(
                max(columns, key = len)
            )
        )

    # print the csv strings
    for row in csvStrings:
        cells = []
        for idx, col in enumerate(row):
            format = '%-' + str(widths[idx]) + "s"
            cells.append(format % (col))
        print ' |'.join(cells)


if __name__ == '__main__':
    printCsvStringListAsTable([
        'col1,col2,col3,col4',
        'val1,val2,val3,val4',
        'abadfafdm,afdafag,aadfag,aadfaf',
    ])

Output:

col1      |col2    |col3   |col4
val1      |val2    |val3   |val4
abadfafdm |afdafag |aadfag |aadfaf

The answer by Alex Hall is definitely better and a terse form of the same code which I have written.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!