Open In App
Related Articles

How to move Files and Directories in Python

Improve Article
Improve
Save Article
Save
Like Article
Like

Python provides functionality to move files or directories from one location to another location. This can be achieved using shutil.move() function from shutil module. shutil.move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory. If the destination already exists but is not a directory then it may be overwritten depending on os.rename() semantics.

Syntax: shutil.move(source, destination, copy_function = copy2)

Parameters:
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 functions like copy, copytree, etc for this parameter.

Return Value: This method returns a string that represents the path of a newly created file.

Example #1: Suppose the structure of directory looks like this –

Python-list-of-directories

Inside Test:

python-move-files-and-dir

Inside A:

python-move-files-and-dir

We want to move directory B into directory A. Below is the implementation.




# Python program to move
# files and directories
  
  
import shutil
  
# Source path
source = "D:\Pycharm projects\gfg\Test\B"
  
# Destination path
destination = "D:\Pycharm projects\gfg\Test\A"
  
# Move the content of
# source to destination
dest = shutil.move(source, destination)
  
# print(dest) prints the 
# Destination of moved directory


Output:

Inside test:

python-move-files-and-dir

Inside A:

python-move-files-and-dir

Example #2: Now let’s suppose we want to move all the sub-directories and files of above directory A to directory G using shutil.copytree() and the destination directory does not exist. Below is the implementation.




# Python program to move
# files and directories
  
  
import shutil
  
# Source path
source = "D:\Pycharm projects\gfg\Test\A"
  
# Destination path
destination = "D:\Pycharm projects\gfg\Test\G"
  
# Move the content of
# source to destination
dest = shutil.move(source, destination, copy_function = shutil.copytree)
  
# print(dest) prints the
# Destination of moved directory


Output:

Inside Test:

python-move-files-and-dir

Inside G:

python-move-files-and-dir


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 29 Dec, 2020
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials