Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prettyprint to a file?

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

like image 250
James.Wyst Avatar asked Jun 24 '13 16:06

James.Wyst


People also ask

How do I import pretty prints?

To use pprint, begin by importing the library at the top of your Python file. From here you can either use the . pprint() method or instantiate your own pprint object with PrettyPrinter() .


2 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) 
like image 141
Stefano Sanfilippo Avatar answered Oct 14 '22 11:10

Stefano Sanfilippo


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) 
like image 28
Gary02127 Avatar answered Oct 14 '22 10:10

Gary02127