2010-10-07 29 views

Trả lời

13

Vui lòng sử dụng pprint.pformat, mà trả về một chuỗi formated mà có thể được đổ trực tiếp vào tập tin.

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

tham khảo:

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

+2

'pprint (DataObject, fout) 'hoạt động giống như tốt. –

+1

Bạn sẽ thấy pformat chậm hơn nhiều so với pprint trực tiếp vào tệp, đặc biệt nếu bạn sử dụng một cấu trúc như 'varname =% s% pprint.pformat (varname)' – boatcoder

2

Đối với 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 
Các vấn đề liên quan