Skip to content

Commit

Permalink
new tip
Browse files Browse the repository at this point in the history
  • Loading branch information
bbelderbos committed May 29, 2024
1 parent e9ee187 commit 3ac8354
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
4 changes: 4 additions & 0 deletions index.md
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,10 @@ This file gets generated by [this script](index.py).

- [Make a terminal plot](notes/20240119105430.md)

## Pprint

- [Pretty print to a file](notes/20240529114443.md)

## Property

- [Computed (and readonly) fields / attributes](notes/20230829122437.md)
Expand Down
21 changes: 21 additions & 0 deletions notes/20240529114443.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 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

0 comments on commit 3ac8354

Please sign in to comment.