Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 17 Jun, 2021

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 do the same using python.

This can be done in two ways:

  • Using os module.
  • Using shutil module.

Source and Destination Folder

Source and destination folders

Source Folders

Destination Folder – before

Method 1: By Using rename() method from os module



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

Firstly import the os module, 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 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: By using move() method from  shutil module

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

Firstly import shutil module, 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 os module. Now move all the files from the list one by one using shutil.move() method.

Python3




import os
import shutil
  
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:
    shutil.move(source + f, destination + f)

Both outputs are the same:

Destination Folder – after

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :