32

I'm using this gist's tree, and now I'm trying to figure out how to prettyprint to a file. Any tips?

James.Wyst
  • 729
  • 2
  • 7
  • 12

4 Answers4

71

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)
Stefano Sanfilippo
  • 29,175
  • 7
  • 71
  • 78
6

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)
Gary02127
  • 3,423
  • 19
  • 19
  • Great, thanks, although I prefer: `with open('output.txt','w') as output: output.write(pprint.pformat(data))` – Andrew Oct 13 '20 at 10:59
  • 1
    @Andrew - Absolutely! A good context block is always the best choice! I will update my answer to make it a better programming example. – Gary02127 Oct 14 '20 at 12:46
0

If I understand correctly, you just need to provide the file to the stream keyword on pprint:

with open(outputfilename,'w') as fout:
    pprint(tree,stream=fout,**other_kwargs)
mgilson
  • 264,617
  • 51
  • 541
  • 636
0
import pprint
outf = open("./file_out.txt", "w")
PP = pprint.PrettyPrinter(indent=4,stream=outf)
d = {'a':1, 'b':2}
PP.pprint(d)
outf.close()

Could not get the stream= in the accepted answer to work without this syntax in Python 3.9. Hence the new answer. You could also improve on using the with syntax to improve on this too.

import pprint
d = {'a':1, 'b':2}
with open('./test2.txt', 'w+') as out:
    PP = pprint.PrettyPrinter(indent=4,stream=out)
    PP.pprint(d)
JGFMK
  • 7,107
  • 4
  • 46
  • 80