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)
Answer from Stefano Sanfilippo on Stack OverflowWhat 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)
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)
How to prettyprint a JSON file?
python 3.x - How to get a pretty print for my input file - Stack Overflow
Pretty-Print JSON Data to a File using Python - Stack Overflow
prettyprint is not pretty when trying to write to text file
You should use the optional argument indent.
header, output = client.request(twitterRequest, method="GET", body=None,
headers=None, force_auth_header=True)
# now write output to a file
with open("twitterData.json", "w") as twitterDataFile:
# magic happens here to make it pretty-printed
twitterDataFile.write(
simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True)
)
You can parse the JSON, then output it again with indents like this:
import json
mydata = json.loads(output)
print json.dumps(mydata, indent=4)
See http://docs.python.org/library/json.html for more info.
I have a very big dictionary I would like to write to a text file. The dictionary in question has values which are lists of very long strings. When I used pprint to write to a text file, I expect something similar to:
{"key0":
["value1"],
"key1":
["value2"]....
}But instead I get a giant mess that totally defeated the purpose of using pprint in the first place. I even tried using a third-party pprintpp and that didnt work either. Does anyone have any idea of how to do this?