Moving Old files to new location using Python

Posted by Afsal on 02-Feb-2024

Hi Pythonistas!

Today we are learning how to automate moving old files to new locations using python. If we are working with lots of files and older files need to move to a new location at proper intervals we easily automate this task using python. All the modules used are available in the standard library itself. Let us jump into the code

Checking the given path exists

if not os.path.exists(source_directory) or not os.path.exists(destination_directory):
     print("Source or destination directory does not exist.")
     return

Check whether the given path exists if any of then does not exist then show a message and returns 

List all the files in source directory

files_to_move = [f for f in os.listdir(source_directory) if os.path.isfile(os.path.join(source_directory, f))]

os.listdir - List all the items in the given directory

os.path.isfile - This check if given path is file if it file then return true

os.path.join - This for concating the source path and file name and return the complete path

Get files creation time

creation_time = datetime.fromtimestamp(os.path.getctime(file_path))

os.path.getctime - Returns the creation timestamp of a file

datetime.fromtimestamp - This convert the timestamp to datetime object

Moving File

shutil.move(file_path, destination_path)

This move the file form the source path to the destination path

Complete code

import os
import shutil
from datetime import datetime, timedelta


def move_old_files(source_directory, destination_directory, days_threshold=30):
    if not os.path.exists(source_directory) or not os.path.exists(destination_directory):
        print("Source or destination directory does not exist.")
        return
    threshold_date = datetime.now() - timedelta(days=days_threshold)
    files_to_move = [f for f in os.listdir(source_directory) if os.path.isfile(os.path.join(source_directory, f))]

    for file_name in files_to_move:
        file_path = os.path.join(source_directory, file_name)
        creation_time = datetime.fromtimestamp(os.path.getctime(file_path))
        if creation_time < threshold_date:
            destination_path = os.path.join(destination_directory, file_name)
            shutil.move(file_path, destination_path)
            print(f"Moved: {file_name}")

if __name__ == "__main__":
    source_directory = "/home/afsal/Downloads"
    destination_directory = "/home/afsal/Documents/backup"
    days_threshold = 30
    move_old_files(source_directory, destination_directory, days_threshold)

I hope this post is useful. We share there types of automation tips in upcoming posts please share valuable suggestions with afsal@parseltongue.co.in