how to send the output of pprint module to a log file

PythonLogging

Python Problem Overview


I have the following code:

logFile=open('c:\\temp\\mylogfile'+'.txt', 'w')
pprint.pprint(dataobject)

how can i send the contents of dataobject to the log file on the pretty print format ?

Python Solutions


Solution 1 - Python

with open("yourlogfile.log", "w") as log_file:
    pprint.pprint(dataobject, log_file)

See the documentation.

Solution 2 - Python

Please use pprint.pformat, which returns a formated string that can be dumped directly to file.

>>> import pprint
>>> with open("file_out.txt", "w") as fout:
...     fout.write(pprint.pformat(vars(pprint)))
... 

Reference:

http://docs.python.org/2/library/pprint.html

Solution 3 - Python

For Python 2.7

logFile = open('c:\\temp\\mylogfile'+'.txt', 'w')
pp = pprint.PrettyPrinter(indent=4, stream=logFile)
pp.pprint(dataobject)   #you can reuse this pp.print

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAKMView Question on Stackoverflow
Solution 1 - PythonlivibetterView Answer on Stackoverflow
Solution 2 - PythonddalexView Answer on Stackoverflow
Solution 3 - PythonKaiwen SunView Answer on Stackoverflow