Thursday 3 May 2012

Started out Working through DougHellmann.com's PrettyPrinter Lesson

Module: pprint
Purpose: Pretty-print data structures

The output is kept on a single line, if possible, and indented correctly when split across multiple lines.

PrettyPrint dictionaries & have them printed and sorted by key
pprint seems to sort the keys for you after python2.5 for both single and multi-line output

Changed in version 2.5: Dictionaries are sorted by key before the display is computed; before 2.5, a dictionary was sorted only if its display required more than one line, although that wasn’t documented.

"Generally, though, if you're writing data structures to a file and want them human-readable and writable, you might want to consider using an alternate format like YAML or JSON." [StackOverFlow Tip]

dataObject = [ (i, { 'a':'A',
               'b':'B',
               'c':'C',
               'd':'D',
               'e':'E',
               'f':'F',
               'g':'G',
               'h':'H',
               })
         for i in xrange(3)
         ]

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

This suggestion

pprint.pprint(dataobject, logFile)

Makes the following code work

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

 

No comments:

Post a Comment