Skip to content
Related Articles

Related Articles

How to move all files from one directory to another using Python ?

View Discussion
Improve Article
Save Article
  • Last Updated : 08 Aug, 2022

In this article, we will see how to move all files from one directory to another directory using Python.  In our day-to-day computer usage we generally copy or move files from one folder to other, now let’s see how to move a file in Python:

This can be done in two ways:

  • Using os module.
  • Using shutil module.

Source and Destination Folder

 

Source Folders

Destination Folder – before

Method 1: Move Files in Python using rename() method from the os module

rename() method takes two arguments first one is the source path and the second one is the destination path, the rename function will move the file at the source path to the provided destination.

Firstly import the os module, store the path of the source directory and path of the destination directory, and make a list of all files in the source directory using listdir() method in the os module. Now move all the files from the list one by one using rename() method.

Code:

Python3




import os
 
source = 'C:/Users/sai mohan pulamolu/Desktop/deleted/source/'
destination = 'C:/Users/sai mohan pulamolu/Desktop/deleted/destination/'
 
allfiles = os.listdir(source)
 
for f in allfiles:
    os.rename(source + f, destination + f)

Method 2: Move Files in Python using the move() method from shutil module

The shutil.move() method takes two arguments first one is the source path and the second one is the destination path, the move function will move the file at the source path to the provided destination.

Firstly import shutil module, and store the path of the source directory and path of the destination directory. Make a list of all files in the source directory using listdir() method in the os module. Now move all the files from the list one by one using shutil.move() method.

Python3




import os
import shutil
source_folder = 'C:/Users/sai mohan pulamolu/Desktop/deleted/source/'
destination_folder = 'C:/Users/sai mohan pulamolu/Desktop/deleted/destination/'
 
allfiles = os.listdir(source_folder)
 
for f in allfiles:
     source = source_folder + f
    destination = destination_folder + f
    if os.path_isfile(source):
      shutil.move(source , destination)

Outputs are the same:

Destination Folder – after


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!