Difference between os.rename and shutil.move in Python

In Python, there are many useful modules. os and shutil modules are two of those useful modules. Today we are going to learn the difference between os.rename and shutil.move in Python.

os.rename vs shutil.move in Python

If you want to know among these two modules os and shutil, which module is better, then you are asking a wrong question. Basically, both can be used in Python program. But you have to determine what should be used in which purpose.

In a single sentence, we can say that shutil is consisting of high-level Python specific functions. shutil is on top of Python’s os module. Thus, we can use the shutil module for high-level operations on files.

Here is an example for both modules,

import shutil
import os
shutil.move("M://source/folder/file.txt", "M://destination/folder/file.txt") # using shutil.move
os.rename("M://source/folder/file.txt", "M://destination/folder/file.txt")  # using os.rename

Using the above code we can move a file from one directory to another. We have used both the modules. ( don’t try to use both modules at the same time, this is just to show you both the modules )

Some basic differences between os.rename and shutil.move

  1. OS module might fail to move a file if the source and destination path is on different file systems or drive.
    But shutil.move will not fail in this kind of cases.
  2. shutil.move checks if the source and destination path are on the same file system or not. But os.rename does not check, thus it fails sometimes.
  3. After checking the source and destination path, if it is found that they are not in the same file system, shutil.move will copy the file first to the destination. Then it will delete the file from the source file. Thus we can say shutil.move is a smarter method to move a file in Python when the source and destination path are not on the same drive or file system.
  4. shutil.move works on high-level functions, while os.rename works on lower-level functions.

 

If you are interested in moving a file from one directory to another you can read this Python tutorial,

2 responses to “Difference between os.rename and shutil.move in Python”

  1. shawon says:

    In the point 3 , “After checking the source and destination path, if it is found that they are not in the same file system, shutil.move will copy the file first to the destination. Then it will delete the file from the DESTINATION file. Thus we can say shutil.move is a smarter method to move a file in Python when the source and destination path are not on the same drive or file system.”
    Should not it be “source file ” insted of “destination file” ?

Leave a Reply

Your email address will not be published. Required fields are marked *