What is the best way to print a table with delimiters in Python

流过昼夜 提交于 2019-12-03 16:46:55

Your shorter solution would work well as something quick and dirty. But if you need to handle large amounts of data, it'd be better to use csv module:

import sys, csv
writer = csv.writer(sys.stdout, delimiter="\t")
writer.writerows(data)

The benefit of this solution is that you may easily customize all aspects of output format: delimiter, quotation, column headers, escape sequences...

I don't think it's going to get much better than your second code snippet... maybe, if you really want,

print "\n".join("\t".join(str(col) for col in row) for row in tab)
monowerker
import sys
import csv

writer = csv.writer(sys.stdout, dialect=csv.excel_tab)
tab = [['a', 1], ['b', 2]]
writer.writerows(tab)

Please do not use concatanation because it creates a new string every time. cStringIO.StringIO will do this kind of job much more efficiently.

It depends on why you want to output like that, but if you just want to visually reference the data you might want to try the pprint module.

>>> import pprint
>>> for item in tab:
...     pprint.pprint(item, indent=4, depth=2)
...
['a', 1]
['b', 2]
>>>
>>> pprint.pprint(tab, indent=4, width=1, depth=2)
[   [   'a',
        1],
    [   'b',
        2]]
>>>

The prettytable library may be useful. It also helps maintain the column alignment and allows additional style customizations.

Example:

# Ref: https://code.google.com/archive/p/prettytable/

import prettytable

# Read the input csv file
with open("input.csv", "r") as input_file:
    table = prettytable.from_csv(input_file)

# Optionally, change the default style
table.set_style(prettytable.PLAIN_COLUMNS)
table.align = "l"
table.valign = "t"

# Write the output ASCII text file
with open("output.txt", "w") as output_file:
    print("{}".format(table.get_string()), file=output_file)

# Optionally, write the output html file
with open("output.html", "w") as output_file:
    print("{}".format(table.get_html_string()), file=output_file)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!