Prettyprint to a file?
35,011
Solution 1
What you need is Pretty Print pprint
module:
from pprint import pprint
# Build the tree somehow
with open('output.txt', 'wt') as out:
pprint(myTree, stream=out)
Solution 2
Another general-purpose alternative is Pretty Print's pformat()
method, which creates a pretty string. You can then send that out to a file. For example:
import pprint
data = dict(a=1, b=2)
output_s = pprint.pformat(data)
# ^^^^^^^^^^^^^^^
with open('output.txt', 'w') as file:
file.write(output_s)
Author by
James.Wyst
Updated on January 31, 2022Comments
-
James.Wyst over 2 years
I'm using this gist's tree, and now I'm trying to figure out how to prettyprint to a file. Any tips?
-
jokoon about 6 yearsDoesn't work anymore, it seems you need to pass stream in the constructor of pprint.PrettyPrinter() like so
pp = pprint.PrettyPrinter(stream=open("thing",'w'))
-
Peter.k over 5 yearsNot working with Python 3.6.5. The output is a list not a graph which is pretty printed on the screen.
-
Noumenon over 4 yearsWorked for me with Python 3.7.2.
-
Andrew over 3 yearsGreat, thanks, although I prefer:
with open('output.txt','w') as output: output.write(pprint.pformat(data))
-
Gary02127 over 3 years@Andrew - Absolutely! A good context block is always the best choice! I will update my answer to make it a better programming example.
-
Justin Furuness over 2 yearsWorks fine for me in python 3.9 as well