Python Forum

Full Version: remove files from folder older than X days
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I made this attempt, it works fine, but I'm not satisfied with it. Couldn't it be done easier in a more pythonic way?
Is there a method for this job in a module? I havent figured it out how to remove the directories as well.

Here is my code:

import os
import time


class FolderCleaner:
    """
    Removes files from older that gives days
    windows env: 'c:\\exports\\subfolder\\'
    """
    path = ''
    days = 0

    def __init__(self, path, days):
        if not os.path.exists(path):
            raise TypeError("folder does not exist")
        self.path = path
        if days < 0 or isinstance(days, bool) or not isinstance(days, int):
            raise ValueError("days must be positive integer")
        self.days = days
        self.clean()

    def clean(self):
        time_in_secs = time.time() - (self.days * 24 * 60 * 60)
        for root, dirs, files in os.walk(self.path, topdown=False):
            for file in files:
                full_path = os.path.join(root, file)
                stat = os.stat(full_path)
                if stat.st_mtime <= time_in_secs:
                    os.remove(full_path)
There was a similar thread in the past few days (not to remove, but logic is very similar),
see this thread: https://python-forum.io/Thread-PyQt-to-d...-two-dates
Can also look at this recent Thread.
As a advice use datetime or pendulum for this as is easier than using time.
So in link over is using pathlib if make some changes it could look like this.
Deleting files older than 60 days,if folders is empty after deleting files,delete these folders.
from pathlib import Path
from datetime import date, timedelta

def walk_dir(starting_dir):
    past_time = date.today() - timedelta(days=60)
    for path in Path(starting_dir).iterdir():
        timestamp = date.fromtimestamp(path.stat().st_mtime)
        if path.is_file() and past_time > timestamp:
            print(f'Delete file --> {path}')
            #path.unlink() # Delete files
        if path.is_dir():
            walk_dir(path)
        try:
            #path.rmdir() # Delete empty folders
            pass
        except (FileNotFoundError, WindowsError):
            pass

if __name__ == '__main__':
    start_path = r'E:\div_code\sound_folder'
    walk_dir(start_path)
pathlib has different approach to work with paths and file-system.
It has a lot functionality that spread in os,glob, and shutil,but not all like eg shutil.rmtree(path)
Can mix in other stuff to pathlib if that's needed.