Python | shutil.copytree () method

Python Methods and Functions

The

Shutil module in Python provides many high-level functions for operations on files and collections of files. It is included in the standard Python utilities. This module helps automate the process of copying and deleting files and directories. 
The shutil.copytree () method recursively copies the entire directory tree rooted at the source (src) to the destination directory. The target directory named (dst) must not exist yet. It will be created during copying. Directory rights and times are copied using

# Python program to explain the shutil.copytree () method

 
# import of the os module

import os 

 
# import shutil module

import shutil 

 
# path

path = 'C: / Users / Rajnish / Desktop / GeeksforGeeks'

 
# List of files and directories
# in & # 39; C : / Users / Rajnish / Desktop / Python.Engineering & # 39;

print ( "Before copying file:"

print (os.listdir (path)) 

 

 
# Source path

src  = 'C: / Users / Rajnish / Desktop / Python.Engineering / source'

  
# Destination path

dest = 'C: / Users / Rajnish / Desktop / Python.Engineering / destination'

  
# Copy the content
# source to destination

destination = shutil.copytree (src, dest) 

 
# List of files and directories
# in & quot; C : / Users / Rajnish / Desktop / Python.Engineering & quot;

print ( "After copying file:"

print (os.listdir (path)) 

 
# Print the path again
# generated file

print ( "Destination path: " , destination)

Output:

 Before copying file: ['source'] After copying file: [' destination', 'source'] Destination path: C: / Users / Rajnish / Desktop / Python.Engineering / destination 

Example # 2:
Using the shutil.copytree () method to copy a file using the shutil.copy method () .

Exit :

 Before copying file: ['source'] After copying file: [' destination', 'source'] Desti nation path: C: / Users / Rajnish / Desktop / Python.Engineering / destination 




Get Solution for free from DataCamp guru

# Python program to explain the shutil.copytr method ee ()

 
# import of the os module

import os 

 
# shutil module import

import shutil 

 
# path

path = 'C: / Users / Rajnish / Desktop / GeeksforGeeks'

 
# List of files and directories
# in & # 39; C: / Users / Rajnish / Desktop / Python.Engineering & # 39;

print ( " Before copying file: "

print (os.listdir (path)) 

 

 
# Source path

src = 'C: / Users / Rajnish / Desktop / Python.Engineering / source'

 
# Destination path

dest = 'C: / Users / Rajnish / Desktop / Python.Engineering / destination'

  
# Copy the content
# source to destination
# using shutil.copy () as a parameter

destination = shutil.copytree (src, dest, copy_function  = shutil.copy) 

 
# List of files and directories
# in & quot; C: / Users / Rajnish / Desktop / Python.Engineering & quot ;

print ( "After copying file : "

print (os. listdir (path)) 

 
# Print the path again
# generated file

print ( "Destination path:" , destination)