Skip to content

Latest commit

 

History

History
21 lines (14 loc) · 582 Bytes

20240529114443.md

File metadata and controls

21 lines (14 loc) · 582 Bytes

pretty print to a file

I was in the Python debugger today and I was wondering how to write a sorted dictionary to a file while there. 💪

And then I learned that pprint's PrettyPrinter can stream to a file, nice! 😎

Here is how:

import pprint

# sort by numeric value descending (here: most listened podcast episodes)
sorted_stats = sorted(stats.items(), key=lambda x: x[1], reverse=True)

# pretty print the dict to a text file
with open('sorted_stats.txt', 'w') as file:
    pp = pprint.PrettyPrinter(stream=file, indent=4)
    pp.pprint(sorted_stats)

#pprint