Python – Copy Directory
To copy directory in Python, import shutil library, call shutil.copytree() function and pass source directory path, and destination directory path as arguments.
The syntax to call shutil.copytree() function to copy a directory from source to destination is
import shutil shutil.copytree(source_folder, destination_folder)
shutil.copytree() function can be used to copy a directory, including all its subdirectories and files, to a new location.
In the following program, we will copy the directory “myfolder” to “myfolder_1”.
import shutil source_dir = 'myfolder' destination_dir = 'myfolder_1' try : shutil.copytree(source_dir, destination_dir) print('Directory copied successfully.') except Exception as e: print('Directory not copied.') print(e)
Directory copied successfully.
In this tutorial of Python Examples, we learned how to copy a directory to a given destination path using shutil.copytree() function, with the help of examples.