Prettyprint to a file?

Question:

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

Asked By: James.Wyst

||

Answers:

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)
Answered By: Stefano Sanfilippo

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

from pprint import pprint

with open(outputfilename, 'w') as fout:
    pprint(tree, stream=fout, **other_kwargs)
Answered By: mgilson

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)
Answered By: Gary02127
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)
Answered By: JGFMK