Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a table to file using python?

I have a neat little table using tabulate:

from tabulate import tabulate
outputList = dictOfOutputs.items()
table = outputList
print tabulate(table)

How do I print this to a text file?

like image 667
DBWeinstein Avatar asked Jul 19 '26 09:07

DBWeinstein


2 Answers

Just write it how you normally would write a string to a file:

with open('table.txt', 'w') as f:
    f.write(tabulate(table))
like image 87
heinst Avatar answered Jul 21 '26 22:07

heinst


The tabulate() function returns a string; just write it to a file:

with open('filename.txt', 'w') as outputfile:
    outputfile.write(tabulate(table))

You can always make print output to a file instead of sys.stdout by using >> redirection:

with open('filename.txt', 'w') as outputfile:
    print >> outputfile, tabulate(table)

or by using the print() function (put from __future__ import print_function at the top of your module if you are using Python 2):

from __future__ import print_function

with open('filename.txt', 'w') as outputfile:
    print(tabulate(table), file=outputfile)
like image 21
Martijn Pieters Avatar answered Jul 22 '26 00:07

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!