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)
Share:
35,011
James.Wyst
Author by

James.Wyst

Updated on January 31, 2022

Comments

  • James.Wyst
    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
    jokoon about 6 years
    Doesn'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
    Peter.k over 5 years
    Not working with Python 3.6.5. The output is a list not a graph which is pretty printed on the screen.
  • Noumenon
    Noumenon over 4 years
    Worked for me with Python 3.7.2.
  • Andrew
    Andrew over 3 years
    Great, thanks, although I prefer: with open('output.txt','w') as output: output.write(pprint.pformat(data))
  • Gary02127
    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
    Justin Furuness over 2 years
    Works fine for me in python 3.9 as well