The itertools, pathlib, and calendar Modules
The only difference is you get tuples instead of lists. I’ve used
chunked() a bunch when laying out cards on a webpage, so in the future, this will mean one less third-party library dependency for me.
I really like the
pathlib module. It feels far more Pythonic than its predecessor. I’m not sure why, but I only discovered it in the last couple years, but evidently it’s been around since Python 3.4.
A common activity when dealing with a directory is to loop over its contents. Prior to 3.12,
Path did have a way of iterating over a directory, but it didn’t handle subdirectories. To do so, you’d write a recursive function to descend into any subdirectories found, and then calling the iteration method once more.
It does all that subdirectory iteration for you, allowing you to iterate over an entire tree. Off to the REPL once more, this time to take a walk. As I’m going to be walking a directory structure, I needed a directory structure. I’m showing it here using the
03:12 It comes with some Unix variations, but not with all, but it’s a good tool. If you don’t have it, it’s worth downloading. As you can see, it descends a directory and prints out a tree version of its contents.
And that would be the
Path object for the
musicians/ subdirectory. Let me stick this in a variable so I can do stuff with it. Now I’m going to walk the path. The
.walk() method returns a series of tuples.
Each row consists of a tuple, and that tuple contains the contents. For example, the
musicians tuple has a list of directories, which is the
vocal/ subdirectories, and the single
readme file inside of it.
This walks the directory, uses the
.stat() method on each one of the files in the directory, and then sums up their size totals, and then counts how many non-files there are in the directory itself. Let me hit Enter … and this is the output for my dummy
Become a Member to join the conversation.