2010-10-07 5 views

risposta

13

Si prega di utilizzare pprint.pformat, che restituisce una stringa formattata che può essere scaricato direttamente in un file.

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

Riferimento:

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

+2

'pprint (DataObject, fout)' funziona altrettanto bene. –

+1

Troverai che pformat è molto più lento di pprint direttamente sul file, specialmente se usi un costrutto come 'varname =% s% pprint.pformat (varname)' – boatcoder

2

Per 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 
Problemi correlati