What is the best way to print delimited tables in Python

I want to print a table mixed with strings and floating point values โ€‹โ€‹as a printout of tab delimited output. Of course I can do this work:

>>> tab = [['a', 1], ['b', 2]] >>> for row in tab: ... out = "" ... for col in row: ... out = out + str(col) + "\t" ... print out.rstrip() ... a 1 b 2 

But I have a feeling that there is a better way to do this in Python, at least for printing each row with the specified delimiter, if not the whole table. A little googling (from here ), and it's already shorter:

 >>> for row in tab: ... print "\t".join([str(col) for col in row]) ... a 1 b 2 

Is there an even better or more Python-ish way?

+4
source share
6 answers

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

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

The advantage of this solution is that you can easily customize all aspects of the output format: separator, quote, column headers, escape sequences ...

+17
source

I donโ€™t think it will be much better than your second piece of code ... maybe if you really want it,

 print "\n".join("\t".join(str(col) for col in row) for row in tab) 
+4
source
 import sys import csv writer = csv.writer(sys.stdout, dialect=csv.excel_tab) tab = [['a', 1], ['b', 2]] writer.writerows(tab) 
+2
source

Do not use concatenation because it creates a new line every time. cStringIO.StringIO will do this job much more efficiently.

0
source

It depends on why you want to output this, but if you just want to visually reference the data, you can try pprint .

 >>> 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]] >>> 
0
source

A prettytable library might be useful. It also helps maintain column alignment and allows you to add additional style settings.

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

All Articles