Search code examples
pythonshutillistdir

Move specified number of files from source folder to destination folder


My goal with this program:

Move a specified number of files from the source folder into the destination folder. For example, if the source folder contains 8 files I want to move the last 4 files to the destination folder. I'm unsure how to go about this and any help would be greatly appreciated.

The code below moves all files.

Code:

import os
import shutil


def moveFiles():
    source_folder = r"path"
    destination_folder = r"path"

    file_names = os.listdir(source_folder)

    for file_name in file_names:
        shutil.move(os.path.join(source_folder, file_name), destination_folder)


def main():
    moveFiles()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        exit()

Solution

  •     for file_name in file_names[4:]:
            shutil.move(os.path.join(source_folder, file_name), destination_folder
    

    Slice file_names from 5th index.