是否打印到文件?

问题描述 投票:26回答:3

我正在使用gist's这棵树,现在我试图弄清楚如何对文件进行漂亮打印。有提示吗?

python hash dictionary tree pretty-print
3个回答
57
投票

您需要的是Pretty Print pprint模块:

pprint

0
投票

如果我理解正确,您只需将文件提供给from pprint import pprint # Build the tree somehow with open('output.txt', 'wt') as out: pprint(myTree, stream=out) 上的stream关键字:

pprint

0
投票

另一个通用替代方法是Pretty Print的with open(outputfilename,'w') as fout: pprint(tree,stream=fout,**other_kwargs) 方法,该方法创建一个漂亮的字符串。然后,您可以将其发送到文件中。例如:

pformat()
© www.soinside.com 2019 - 2024. All rights reserved.