![]() |
VOOZH | about |
shutil.copytree() method in Python is used to recursively copy an entire directory tree from a source to a destination. It copies all the contents, including files and subdirectories, preserving the directory structure.
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=copy2, ignore_dangling_symlinks=False)
Parameters:
Return Value: This method returns a string which represents the path of newly created directory.
This code demonstrates how to copy an entire directory, including its contents, from the source path to the destination path using the shutil.copytree() method.
Output
Before copying file:
['copy_tree_example.py', 'source']
After copying file:
['copy_tree_example.py', 'destination', 'source']
Destination path: C:\Users\GFG0589\Desktop\vs\destination
Explanation: The shutil.copytree() method is used to copy the entire content of the source directory (src) to the destination directory (dest). Theos.listdir() function is called before and after to show the directory contents. The final output prints the path of the newly created directory.
This example shows how to copy the contents of a directory from the source to the destination using shutil.copytree() with a custom copy function, specifically shutil.copy().
Output
Before copying file:
['source']
After copying file:
['destination', 'source']
Destination path: C:\Users\GFG0589\Desktop\vs\destination
Explanation: Here, shutil.copytree() is used to copy the content from the source directory to the destination directory. Instead of the default copy2(), shutil.copy() is passed as the copy_function argument to handle the file copying. This method copies the content with basic metadata. The os.listdir() function is used before and after the copy to display changes in the directory, and the destination path is printed at the end.