In this article, we will be learning on moving a collection of files and folders where there may be files/folders with the same name as in the source name in the destination. So that we may need to overwrite the existing destination file with the source file.
The shutil.move() method is used to move a file or directory from one place to another. If there is an existing directory or file in the destination which will be checked using os.path.isfile() and os.path.isdir() method, then it will be deleted using os.remove() method, and if it is a directory then it will be deleted using shutil.rmtree() method then the file will be moved.
shutil.move(source, destination, copy_function = copy2)
- source: A string representing the path of the source file.
- destination: A string representing the path of the destination directory.
- copy_function (optional): The default value of this parameter is copy2. We can use other copy function like copy, copytree, etc for this parameter.
Return Value: This method returns a string which represents the path of newly created file.
Call shutil.move(source, destination) method by replacing source and destination by entire path in string format. Using the above method, the files with the same name will be overwritten with the file content as of the source file
Example 1: Program to move a folder containing a file using python.
Desktop |_folder_ |_Geeks folder |_test folder_gfg.txt
Example 2: Program to overwrite a folder containing a file using python.
Desktop |_folder_ |_Geeks folder_test folder_gfg.txt |_test folder_gfg.txt
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course