I'm using this gist's tree, and now I'm trying to figure out how to prettyprint to a file. Any tips?
Asked
Active
Viewed 4.1k times
44
-
Is the output format somewhat relevant (other than being properly formatted)? – Stefano Sanfilippo Jun 24 '13 at 16:38
-
Same way you'd write anything else to a file, no? – Matt Ball Jun 24 '13 at 16:38
-
@Stefano There are multiple keys and values, which should be clear in the format. – James.Wyst Jun 24 '13 at 16:42
-
@MattBall If I printed it with a .write(), the output would essentially be all one line-utterly unreadable. – James.Wyst Jun 24 '13 at 16:44
4 Answers
86
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
- 32,265
- 7
- 79
- 80
-
2Doesn'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'))` – jokoon Mar 25 '18 at 11:15
-
1Not working with Python 3.6.5. The output is a list not a graph which is pretty printed on the screen. – Peter.k Feb 06 '19 at 18:03
-
2
-
12
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)

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

Justin Furuness
- 685
- 8
- 21

mgilson
- 300,191
- 65
- 633
- 696
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
- 8,425
- 4
- 58
- 92