How to move a file from one directory to another in Python

In this Python tutorial, we will see how to move a file from one directory to another in Python. We can achieve our goal to move a file from one folder to another using any of these modules

  • OS Module in Python
  • Shutil Module in Python

Learn,

Move a file from one directory to another in Python using os

Here we will use the os module to move a file in Python.

Suppose we have a folder structure like this:

move a file from one directory to another in Python

Folder structure

Drive name is M

In that drive, we have a folder named codespeedy.



In codespeedy folder, we have two folders

  • folder1
  • folder2

Now suppose we have a file in folder1. The file name is: hello.txt

So the path of the file is:

M://codespeedy/folder1/hello.txt

And we need to move this file to the directory folder2 using Python program.

We are going to use the os module in our program. So we have to import the module first.

import os

Our destination path is:

M://codespeedy/folder2/hello.txt

Now the Python program to move the file from folder1 to folder2 will be:

import os
os.rename("M://codespeedy/folder1/hello.txt", "M://codespeedy/folder2/hello.txt")

If you run this Python program, your file will be moved from folder1 to folder2.

Here we have used os.rename() method.

Parameters used:

  • The first parameter is double quoted and it is the source path of the file
  • The second parameter is also double quoted and it is the destination path of the file.

Note: If you change the file name in the second path, then your file will be moved but the filename will be changed as well.

You must have to mention the full path including the file name.

Move a file from one folder to another in Python using shutil

This time we are taking the previous example again.

We have a folder in drive named codespeedy.

In that folder, we have two folders.

  1. folder1
  2. folder2

Now we have a file hello.txt.

But this time the file is located in folder2

Let’s move the file from folder2 to folder1 using shutil module in Python.

import shutil
shutil.move("M://codespeedy/folder2/hello.txt", "M://codespeedy/folder1/hello.txt")

If you run this Python program your file will be moved to folder1 from folder2.

Parameters used in shutil.move() method in Python

  • The first parameter is double quoted and it is the source path of the file
  • The second parameter is also double quoted and it is the destination path of the file.

You may also learn,

Leave a Reply

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