I’m looking for a solution to the following:
Given today’s date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January.
Then based on that, I need to be able to iterate through a directory and find all files that were created that month.
Bonus points would include finding the most current file created for the previous month.
Simplest, where
adateis an instance ofdatetime.date:There’s no real way in most Unix filesystems to determine when a file was created, as they just don’t keep that information around. Maybe you want the “latest inode change time” (could be creation, could be some other inode change):
Of course, this could mean that month in any year — you sure, in both questions, you don’t want the year as well as the month? That would be the
.yearattribute.Anyway, sticking with month only, as per your question, for a single directory (which is the letter of your question), to get all files you can use
os.listdir(for a tree rooted in the directory you’d useos.walkinstead). Then to keep only those with latest-inode-change in a given month:You could code this as a list comprehension, but there’s just too much code there for a listcomp to be elegant and concise.
To get the “latest” time, you can either repeat the os.stat call (slower but probably simpler), or change cmonth to return the timestamp as well. Taking the simple route:
Now, the “most recent file” given a list
filesof files’ full names (i.e. inc. path) isOf course there are many degrees of freedom in how you put this all together, depending on your exact specs — given that the specs don’t appear to be necessarily precise or complete I’ve chosen to show the building blocks that you can easily tweak and put together towards your exact needs, rather than a full-blown solution that would likely solve a problem somewhat different from your actual one;-).
Edit: since the OP clarified that they need both year and month, let’s see what changes would be needed, using tuples
ymfor(year, month)in lieu of the bare month:Nothing deep or difficult, as you can see (I also added comments to show how to skip subdirectories if you’re worried about those). And btw, if what you actually need is to walk a subtree, rather than just a directory, that change, too, is pretty localized: