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 3.0k times
32
-
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
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)
![](../../users/profiles/2344584.webp)
Stefano Sanfilippo
- 29,175
- 7
- 71
- 78
-
1Doesn'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
-
1
-
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)
![](../../users/profiles/3159059.webp)
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
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)
![](../../users/profiles/495157.webp)
JGFMK
- 7,107
- 4
- 46
- 80