Python Forum
remove files from folder older than X days
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
remove files from folder older than X days
#1
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)
Reply
#2
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
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 532 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  Installing Older Version Of Numpy & Pandas knight2000 6 1,771 Aug-30-2023, 10:58 AM
Last Post: knight2000
  Rename files in a folder named using windows explorer hitoxman 3 735 Aug-02-2023, 04:08 PM
Last Post: deanhystad
  Rename all files in a folder hitoxman 9 1,482 Jun-30-2023, 12:19 AM
Last Post: Pedroski55
  How to loop through all excel files and sheets in folder jadelola 1 4,461 Dec-01-2022, 06:12 PM
Last Post: deanhystad
  python gzip all files from a folder mg24 3 3,985 Oct-28-2022, 03:59 PM
Last Post: mg24
  delete all files and subdirectory from a main folder mg24 7 1,586 Oct-28-2022, 07:55 AM
Last Post: ibreeden
  Remove tag several xml files mfernandes 5 3,798 Sep-20-2022, 01:42 AM
Last Post: Pedroski55
  Merge all json files in folder after filtering deneme2 10 2,336 Sep-18-2022, 10:32 AM
Last Post: deneme2
  How split N days between specified start & end days SriRajesh 2 1,331 May-06-2022, 02:12 PM
Last Post: SriRajesh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020