Prettyprint到文件?

Jam*_*yst 24 python tree hash dictionary pretty-print

我正在使用这个要点的树,现在我正在试图弄清楚如何对文件进行漂亮打印.有小费吗?

Ste*_*ppo 53

你需要的是Pretty Print pprint模块:

from pprint import pprint

# Build the tree somehow

with open('output.txt', 'wt') as out:
    pprint(myTree, stream=out)
Run Code Online (Sandbox Code Playgroud)

  • 不再工作了,看来你需要在 pprint.PrettyPrinter() 的构造函数中传递流,就像 `pp = pprint.PrettyPrinter(stream=open("thing",'w'))` (2认同)
  • 使用 Python 3.7.2 为我工作。 (2认同)

Gar*_*127 7

另一个通用的替代方法是 Pretty Print 的pformat()方法,它创建一个漂亮的字符串。然后,您可以将其发送到文件中。例如:

import pprint
data = dict(a=1, b=2)
output_s = pprint.pformat(data)
#          ^^^^^^^^^^^^^^^
with open('output.txt', 'w') as file:
    file.write(output_s)
Run Code Online (Sandbox Code Playgroud)

  • @安德鲁-当然!一个好的上下文块永远是最好的选择!我将更新我的答案以使其成为更好的编程示例。 (2认同)