How To Copy and Move File with Python shutil Module? – POFTUT

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

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.

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.

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)