Skip to content

Latest commit

 

History

History
82 lines (55 loc) · 2.54 KB

Python_Clean_your_download_folder.md

File metadata and controls

82 lines (55 loc) · 2.54 KB



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'

Input

Import libraries

import os
import shutil
from datetime import datetime, timedelta

Setup Variables

  • 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)

Model

## 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)

Output

print("The files has been successfully moved to 'files_to_delete' folder.")