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