All You Need to Know About Python shutil.move()

The shutil.move() is a function belonging to the module shutilshutil, or shell utilities, is a Python module that allows the user to perform advanced operations on system files and a collection of files. This module can automate processes that deal with deletion or copying.

About the Function

shutil.move() function relocates a file or an entire directory from the source location to the specified location.

Function Syntax and Parameters

shutil.move(src, dst, copy_function)
  • src(source) – Accepts a string type which represents the path of the source file
  • dst(destination) – Accepts a string type which represents the path of the destination directory.
  • copy_function – The default copy function set by the module is copy2. However, you can change it to another copy function that suits your need.

Returns

The function returns a string type that represents the path of a newly created file.

Importing the Module

As of Python 3.10, shutil is included in the Python Standard Library under the File and Directory Access category. Make sure to follow along and run the commands side-by-side on your browser using this!

import shutil

Exploring the Function

Moving File From Source to Non-Existing Destination Using shutil.move(copy_function=copy2)

Here, we have created file srcFile (fig. 1), which consists of a sample text document SampleText (fig. 2)

Python shutil.move()
fig. 1
SampleText
fig. 2

In this program, we are taking srcFile and moving it to a destination that does not exist yet. Therefore, copy2() creates a new directory destFile which moves the contents of the srcFile to. After relocating the contents of srcFile, i.e., SampleText, srcFile itself is deleted. We are using os.listdir() to list the directories located in the specified location.

import os   
import shutil 
  
# Location where the file operations will take place
path = 'C:/Users/Admin/Desktop/PythonPool'
  
# Listing all the files currently in C:/Users/Admin/Desktop/PythonPool
print("Existing files before running shutil.move(copy2): ") 
print(os.listdir(path)) 
  
  
# Location of the current source file
source = 'C:/Users/Admin/Desktop/PythonPool/srcFile'
  
# Location of where you want your new dest file created
destination = 'C:/Users/Admin/Desktop/PythonPool/destFile'
  
# Moving source to newly created destination 
dest = shutil.move(source, destination) 
  
# Listing all the file(s) currently in C:/Users/Admin/Desktop/PythonPool -
# After running the function
print("Existing files after running shutil.move(copy2): ") 
print(os.listdir(path)) 
  
# Current location of the file in the newly created folder 
print("Destination of reloacated source content: ", dest) 

Output

Existing files before running shutil.move(copy2): 
['destFile', 'srcFile']
Existing files  after running shutil.move(copy2): 
['destFile']
Destination:  C:/Users/Admin/Desktop/PythonPool/destFile\srcFile

Results

destFile
fig. 3
SampleText-destFile
fig. 4

In fig.3 and fig.4, you can see the newly created destination folder by copy2() and the contents of srcFile.

Moving File From Source to Existing Destination Using shutil.move(copy_function=copytree)

Here we have the same source folder srcFolder with the same contents. Note that we have already created destFile.

destFile-srcFolder
fig. 5
SampleText
fig. 6

We will be moving the srcFile and its content to a pre-existing file location in the code below. Since the destination already exists, we will be using the copytree() function.

import os   
import shutil 
  
# location where the file operations will take place
path = 'C:/Users/Admin/Desktop/PythonPool'
  
# listing all the files currently in C:/Users/Admin/Desktop/PythonPool
print("Existing files before running shutil.move(copytree): ") 
print(os.listdir(path)) 
  
  
# Location of the current source file
source = 'C:/Users/Admin/Desktop/PythonPool/srcFile'
  
# Location of where you want your new dest file created
destination = 'C:/Users/Admin/Desktop/PythonPool/destFile'
  
# moving source to pre-existing location using copytree
dest = shutil.move(source, destination, copy_function = shutil.copytree) 
  
# listing all the file(s) currently in C:/Users/Admin/Desktop/PythonPool -
# after running the function
print("Existing files  after running shutil.move(copytree): ") 
print(os.listdir(path)) 
  
# Current location of the file in the folder 
print("Destination of relocated src content: ", dest) 

Output

Existing files before running shutil.move(copytree): 
['destFile', 'srcFile']
Existing files  after running shutil.move(copytree): 
['destFile']
Destination of relocated src content:  C:/Users/Admin/Desktop/PythonPool/destFile\srcFile

Results

Unlike copy2, srcFile doesn’t get deleted upon relocation(fig. 7 & fig. 8).

destFile
fig. 7
srcFile-in-destFile
fig. 8

Overwriting files and folders with shutil.move()

In the following program, we will be looking at how we can overwrite directories using the shutil.move() function.

import os
import shutil

# Location of the Parent Folder
path = 'C:/Users/Admin/Desktop/PythonPool'

# Parent Folder contents before running the command
print("Before function call:")
print(os.listdir(path))

# Source and Destination location
source = 'C:/Users/Admin/Desktop/PythonPool/srcFile'
destination = 'C:/Users/Admin/Desktop/PythonPool/destFile'

# Checking if file already exists in destination

# if srcFile is a directory
if os.path.isdir(destination+'/'+'srcFile'):
		print('srcFile exists in the destination path!')
		shutil.rmtree(destination+'/'+'srcFile')
	
# if srcFile is a file
elif os.path.isfile(destination+'/'+'srcFile'):
		os.remove(destination+'/'+'srcFile)
		print('srcFile deleted in destFile')

# Moving  the content from source to destination and saving the return in dest
dest = shutil.move(source, destination)


# Parent Folder contents after running the command
print("After function call:")
print(os.listdir(path))

# Path of the new folder
print("Destination path:", dest)

We are trying to pass .move() to relocate srcFile into destFile. But before that actual process takes place, we are making sure the file doesn’t contain srcFile already. The condition statement looks out for the source file/directory with the name srcFile. If a directory already exists, it is removed using shutil.rmtree. If a file already exists, os.remove() is implemented. srcFile is transferred to the destination after deletion processes.

Output

Before function call:
[ 'destFile', 'srcFile' ]
After function call:
['destFile']
Destination path: C:/Users/Admin/Desktop/PythonPool/destFile\srcFile

Using Python glob with shutil.move()

glob() can provide us with a rundown of multiple directories based on our needs. glob() can work well with move() to relocate an n number of directories or files at once.

import glob
import shutil
 
# iterating through each source files with the matching characters
for eachSrc in glob.glob("Sample_Directories"):
    shutil.move(eachSrc, dest)

shutil.move() vs os.rename()

shutil.move()os.rename()
shutil.move() checks if the source and destination are on the same file system. If not, it’s sent to the new file system and deleted from the source destination. os.rename fails to check if the source and destination are on the same disk.
Therefore, shutil.move() can move files to their destination despite their location.Thus, os.rename might fail to move a file if the destination is located on another disk or file system.
shutil.move() works on higher-level functions.os.rename() works on lower-level functions

Common Errors while Using shutil.move()

[WinError 32] The process cannot access the file because it is being used by another process

This is most likely because contents from the source file are being edited or undergoing a process. This prevents windows from giving Python the permission to manipulate the file contents. Thereby, make sure the files you’re working with are all idle.

FAQs on Python shutil.move()

How is shutil.move() different from shutil.copy()?

After shutil.copy(), the file will always be in both locations. However, in shutil.move(), all the files will only be in the destination folder most of the time. .move() can move entire file directories whereas .copy() can only move a single file at a time.

Conclusion

Hence, We have gone through the shutil module function that is .move()and its capabilities. We demonstrated how the function could be used to move files from their source location to their destination. Seen how it provides us options on the method we want to transfer source files. Despite its similarities to os.rename, we’ve seen how .move() is more advantageous.

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
PRAR
PRAR
1 year ago

What are the exceptions that these two methods can throw?

Pratik Kinage
Admin
1 year ago
Reply to  PRAR

According to source code, it throws Error, OSError, and PermissionError. You can check here.