'Iterate over files in main folder, sort by date, only keep the most recent "n" files based on input and move the rest to the archive folder

My goal with this program:

  1. Iterate over all files in a folder (Main/Source Folder)
  2. Sort by date
  3. Only keep the most recent "n" files
  4. Move rest to an archive folder

For example: I have a folder with 10 files, I only want to keep the first 5 files in the Main/Source folder and move the rest to the archive folder.

So far I Sort the list of files based on the last modification time in ascending order, then Iterate over the sorted list of files and print the file path along with the last modification time of the file.

I'm lost on how to iterate over the sorted files and move the specified files into the archive directory based on the most recent "n" files.

Main:

import os

def main():
    sort()

Sort:

def sort_files():
    dir_name = r"Path"
    # Get list of all files only in the given directory
    list_of_files = filter(lambda x: os.path.isfile(os.path.join(dir_name, x)),
                           os.listdir(dir_name))
    # Sort list of files based on last modification time in ascending order
    list_of_files = sorted(list_of_files,
                           key=lambda x: os.path.getmtime(os.path.join(dir_name, x)),reverse=True
                           )
    # Iterate over sorted list of files and print file path
    # along with last modification time of file
    for file_name in list_of_files:
        file_path = os.path.join(dir_name, file_name)
        timestamp_str = time.strftime('%m/%d/%Y :: %H:%M:%S',
                                      time.gmtime(os.path.getmtime(file_path)))
        print(timestamp_str, ' -->', file_name)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source