【问题标题】:Prettyprint to a file?漂亮打印到文件?
【发布时间】:2013-06-21 06:12:11
【问题描述】:

我正在使用这个gist's 树,现在我正在尝试弄清楚如何将漂亮打印到文件中。有什么建议吗?

【问题讨论】:

  • 输出格式是否有些相关(除了正确格式化)?
  • 与将其他内容写入文件的方式相同,不是吗?
  • @Stefano 有多个key和value,格式上要清楚。
  • @MattBall 如果我用 .write() 打印它,输出基本上都是一行 - 完全不可读。

标签: python hash dictionary tree pretty-print


【解决方案1】:

您需要的是 Pretty Print pprint 模块:

from pprint import pprint

# Build the tree somehow

with open('output.txt', 'wt') as out:
    pprint(myTree, stream=out)

【讨论】:

  • 不工作了,看来你需要在 pprint.PrettyPrinter() 的构造函数中传递流,就像这样pp = pprint.PrettyPrinter(stream=open("thing",'w'))
  • 不适用于 Python 3.6.5。输出是一个列表,而不是在屏幕上漂亮打印的图表。
  • 使用 Python 3.7.2 为我工作。
  • 在 python 3.9 中也适用于我
【解决方案2】:

如果我理解正确,您只需将文件提供给pprint 上的stream 关键字:

from pprint import pprint

with open(outputfilename, 'w') as fout:
    pprint(tree, stream=fout, **other_kwargs)

【讨论】:

    【解决方案3】:

    另一个通用替代方法是 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)
    

    【讨论】:

    • 很好,谢谢,虽然我更喜欢:with open('output.txt','w') as output: output.write(pprint.pformat(data))
    • @Andrew - 绝对!一个好的上下文块永远是最好的选择!我将更新我的答案,使其成为更好的编程示例。
    【解决方案4】:
    import pprint
    outf = open("./file_out.txt", "w")
    PP = pprint.PrettyPrinter(indent=4,stream=outf)
    d = {'a':1, 'b':2}
    PP.pprint(d)
    outf.close()
    

    如果没有 Python 3.9 中的这种语法,接受的答案中的 stream= 将无法正常工作。因此有了新的答案。您也可以改进使用 with 语法来改进这一点。

    import pprint
    d = {'a':1, 'b':2}
    with open('./test2.txt', 'w+') as out:
        PP = pprint.PrettyPrinter(indent=4,stream=out)
        PP.pprint(d)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 2021-10-10
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2016-02-20
      相关资源
      最近更新 更多