How To Copy and Move File with Python shutil Module?


Python provides different modules for copying and moving files. In this tutorial we will learn how to copy, move and operate recursively files with Python shutil Module.

Copy Directories and Folders Recursively with copytree() Function

We will start by copying source path directories and folders to the destination path recursively. Recursively means copying all current level and sublevel files and folders. We will use copytree() function which will get two parameters where first one is the source path we want to copy and the second one is the destination path we want to copy to. In this example we will copy files location in path

import shutil

shutil.copytree("/home/ismail/Downloads/","/home/ismail/Documents/")

Copy Files and Directories/Folders Recursively

If we need to copy the files inside the directories we need to use copy() function. We will provides the source and destination paths again.

import shutil

shutil.copy("/home/ismail/Downloads/","/home/ismail/Documents/")

Move Files and Directories/Folders Recursively

Another practice is moving files recursively. We can move files and folder/directories recursively with the move() function like below.

import shutil

shutil.move("/home/ismail/Downloads/","/home/ismail/Documents/")

Ignore Given Files, Folders and Directories While Copying and Moving

While copying we may need to ignore given files or folders. We will provide ignore parameter with  ignore_function() like below in order to ignore given files and folders. In this case we will ignore file or folder names backup like below.

import shutil

shutil.copytree("/home/ismail/Downloads/","/home/ismail/Documents/",ignore=ignore_function('backup'))

Ignore Given File Extensions While Copying and Moving

If we need to ignore given file extension we can use ignore_patterns() function for the ignore parameter like below. In this example we will ignore .py and .sh extensions.

import shutil

shutil.copytree("/home/ismail/Downloads/","/home/ismail/Documents/",ignore=ignore_patterns('*.py','*.sh'))

LEARN MORE  What Is Computer Clipboard (Pasteboard)?

Leave a Comment