Print results in MySQL format with Python

前端 未结 5 519
-上瘾入骨i
-上瘾入骨i 2020-12-05 01:21

What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like tha

5条回答
  •  半阙折子戏
    2020-12-05 01:38

    You need to do two passes:

    1. Calculate the column widths
    2. Print the table

    So

    table = cur.fetchall()
    widths = [0]*len(table[0])  # Assuming there is always one row
    for row in table:
        widths = [max(w,len(c)) for w,c in zip(widths,row)]
    

    Now you can print the table trivially.

    Remember the string.rjust method when printing the numbers.

    Update

    A more functional way of calculating widths is:

    sizetable = [map(len,row) for row in table]
    widths = map(max, zip(*sizetable))
    

提交回复
热议问题