I saw a script written in PowerShell that removed old PowerShell logs and any empty folders that would result, and I wanted to see if I could replicate it in Python. Basically, the script will examine the FOLDER_PATH for files aged older than FILE_AGE_DAYS (7 in this case) and remove them. After removing the files it will check if there any empty folders in the FOLDER_PATH and remove those too. A danger point to be aware of when running the script: You have to make sure that FOLDER_PATH is correct. Running it with FOLDER_PATH = "C:\" for example might have very bad consequences. I tried to include some Python typing also, but the script is not particularly long or complicated, so might have been overkill.
import os
import pathlib
import time
FOLDER_PATH: str = "D:\\Garbage\\"
FILE_EXT: str = ".txt"
FILE_AGE_DAYS: float = 7
def remove_folder(path):
try:
os.rmdir(path)
print(f"{path} folder removed !")
except OSError as error:
print(error)
print("Folder could not be removed.")
def remove_file(path):
try:
os.remove(path)
print(f"{path} file removed !")
except OSError as error:
print(error)
print("File could not be removed.")
def get_file_or_folder_age(path) -> float:
# Get the modification time of the file is seconds
mod_time = os.path.getmtime(path)
return mod_time
def main():
# Initialise counters
deleted_folders_count: int = 0
deleted_files_count: int = 0
# Path to test
path: str = FOLDER_PATH
# Specify number of days to look back
days: float = FILE_AGE_DAYS
# Convert days to seconds
# time.time() returns current time in seconds
seconds: float = time.time() - (days * 24 * 60 * 60)
# Check if files exist that are older than 'days' amount
if os.path.exists(path):
# Iterate over files
for root_folder, folders, files in os.walk(path):
for f in files:
file_path = os.path.join(root_folder, f)
file_extension = pathlib.Path(file_path).suffix
# Check age and extension, if old .txt: remove
if seconds >= get_file_or_folder_age(file_path) and file_extension == FILE_EXT:
remove_file(file_path)
deleted_files_count += 1
else:
print(f'"{path}" not found')
# Check if empty folders exist
if os.path.exists(path):
# Iterate over folders
for root_folder, folders, files in os.walk(path):
for folder in folders:
folder_path = os.path.join(root_folder, folder)
# Check if folder is empty, if yes: remove
if len(os.listdir(folder_path)) == 0:
remove_folder(folder_path)
deleted_folders_count += 1
else:
print(f'"{path}" not found')
print(f"Total files deleted: {deleted_files_count}")
print(f"Total folders deleted: {deleted_folders_count}")
if __name__ == '__main__':
main()