Carl Sagan
Carl Sagan

Reputation: 982

Python: Recusively remove file folders greater than x days old

I have the following directory structure:

/year/month/day/file.txt

and what I'd like to is to delete entire directories where the /year/month/day is greater than x number of days.

Additionally, if the x number of days exceeds the days in the current month, it deletes the day/ folders from the previous month.

For example: If today is January 15th, and the x number of days to remove is 20, then the script should remove everything but the last 5 days in December.

Any ideas?

Upvotes: 1

Views: 1884

Answers (1)

abarnert
abarnert

Reputation: 365707

for year in os.listdir('.'):
    for month in os.listdir(year):
        for day in os.listdir(os.path.join(year, month)):
            date = datetime.date(int(year), int(month), int(day))

Now you can use the utilities in the date class. When you've decided to remove a entire directory, use shutil.rmtree.

For example:

today = datetime.date.today()
for year in os.listdir('.'):
    for month in os.listdir(year):
        for day in os.listdir(os.path.join(year, month):
            date = datetime.date(int(year), int(month), int(day))
            age = today - date
            if age > datetime.timedelta(days=20):
                shutil.rmtree(os.path.join(year, month, day))

Upvotes: 3

Related Questions