32
votes

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

4
Is the output format somewhat relevant (other than being properly formatted)? - Stefano Sanfilippo
Same way you'd write anything else to a file, no? - Matt Ball
@Stefano There are multiple keys and values, which should be clear in the format. - James.Wyst
@MattBall If I printed it with a .write(), the output would essentially be all one line-utterly unreadable. - James.Wyst

4 Answers

71
votes

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)
6
votes

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)
0
votes

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)
0
votes
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)