Last Updated: Sunday 28th April 2013

Renaming (in Python it's known as moving) a file in Python is really simple, and can be done in very few lines thanks to a handy module called shutil.

shutil has a function called move that does precisely what the function name implies. It moves files or directories from one location to another.

Here's a really simple, yet complete example:

Simple stuff. This function takes in the source file or directory and moves it to the destination file or directory.

shutil.copy vs os.rename

If the file or directory is on the current local file system, shutil.move uses os.rename to move the file or directory. Otherwise, it uses shutil.copy2 to copy the file or directory to the destination and then deletes the source.

The reason we useĀ shutil.move instead of os.rename is because of the reason above. The function shutil.move already takes care of the case where a file is not on the current file system and it handles copying directories over to the destination as well. Any exceptions that os.rename throws are also handled properly in shutil.move, so there is no need to worry about them.

shutil.move does throw its own exceptions in the form of shutil.Error. It does this when either the destination file or directory already exists or if you try to copy the source file or directory onto/into itself.

Unfortunately, there is no option in shutil.move to provide a callback function for measuring progress. You would have to write your own copy function for that, and it would likely be a little bit slower due to the need to count the files and measure their size.

It's really that simple. The only other thing to note is that if on the current file system, the time for our call to the move function will be instantaneous, while when used to move to a separate drive, for example, the call will take the same amount of time as a typical copy operation.

If you are interested in seeing how the shutil.move function was implemented, go to this link for the source code.

Super short, super succinct, and super awesome.

Later Pythonistas!

To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.

About The Author

  • northteam

    I find a typo. “shutil.copy vs os.rename” should be “shutil.move vs os.rename”.