Template request | Bug report | Generate Data Product
Tags: #python #automation #clean_folder
Author: Mohit Singh
Description: This notebook will go through your given folder and check each file last modification time, and if it's been more than 30 days it will move those file to new folder 'files_to_delete'
import os
import shutil
from datetime import datetime, timedelta
path
: path of folder to be clean
## taking the folder path to be clean
path = input("Enter the folder path: ")
## path of folder to be clean
folder_path = os.path.join(os.path.expanduser('~'), path)
## path of new folder
to_delete_path = os.path.join(os.path.expanduser('~'), 'files_to_delete')
## creating 'to_delete' folder, if does not exists already
if not os.path.exists(to_delete_path):
os.makedirs(to_delete_path)
## getting list of all the files
files = os.listdir(folder_path)
## getting current time
now = datetime.now()
## iterating over the list of files
for file in files:
## get the file path
file_path = os.path.join(folder_path, file)
## get the file modification date
modification_date = datetime.fromtimestamp(os.path.getmtime(file_path))
## calculate the time difference
time_difference = now - modification_date
## if the file is older than 30 days
## moving the file to 'to_delete' folder
if time_difference > timedelta(days=30):
shutil.move(file_path, to_delete_path)
print("The files has been successfully moved to 'files_to_delete' folder.")