There is a script that deletes files using a temporary stamp. Deletion with recursion clears nested directories. After the script, empty directories remain. Tell me how else to delete and cleaned directories.

import os import datetime for dirpath, dirnames, filenames in os.walk(r'C:\py\dir_for_remove'): for file in filenames: curpath = os.path.join(dirpath, file) file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath)) if datetime.datetime.now() - file_modified > datetime.timedelta(minutes=5): os.remove(curpath) 
  • if you are satisfied with the answer, click on the checkmark that is to the left of the answer and the person who wrote it will be pleased. - garrythehotdog

1 answer 1

Try this option:

 import os from datetime import datetime, timedelta for root, dirs, files in os.walk(r'C:\py\dir_for_remove', topdown=False): for file in files: curpath = os.path.join(root, file) file_modified = datetime.fromtimestamp(os.path.getmtime(curpath)) if datetime.now() - file_modified > timedelta(minutes=5): os.remove(curpath) # Проходим по директориями и удаляем пустые for d in dirs: curpath = os.path.join(root, d) if not os.listdir(curpath): os.rmdir(curpath) 

topdown=False - changes the traversal order from end to beginning, which will help when deleting folders

  • can be wrapped in a recursive function? so that unlimited nesting is also cleaned? - Eugene Dennis
  • Thanks, option gil9red helped. - Vadim
  • @EugeneDennis, os.walk itself works "recursively" - will go through all subfolders and files. At each iteration, root is the current folder, and dirs and files are subfolders and files - gil9red
  • one
    @Vadin, this is good, otherwise I did not have the opportunity to test :) If it helped you, rate and accept the answer :) - gil9red
  • one
    @EugeneDennis, because of the reverse order of the folders will be removed - gil9red