Python : How to move files and Directories ?

In this article we will discuss different ways to move files and directories in python.

In python we have a shutil module that provides various files related operations.  To import the shutil module use following line,

import shutil

It also provides functions to move files i.e.

shutil.move(src, dst)

It accepts source and destination path as string and moves the source file/directory pointed by src to the destination location pointed by dst and returns the destination path.

Both destination and source paths can be relative or absolute. Let’s use this to move files and directories,

Move a file to an another directory

Pass the source file path as string in first parameter and destination directory path as string in second parameter,

newPath = shutil.move('sample1.txt', 'test')

it will move the file to that directory and returns the path of moved file as string i.e.

test/sample1.txt

Some Points to remember:

  • If destination directory doesn’t exists then it will create a file with that name.
  • If there was already a file with same name in destination directory, then it will be overwritten.
  • If in destination path any intermediate directory does not exists or path is not valid then it will cause an error,
    • FileNotFoundError: [Errno 2] No such file or directory: ‘test3/test/’

Move a file with a new name

In the destination path we can also pass the new name of file, it will move the source file to that location with new name i.e.

newPath = shutil.move('sample2.txt', 'test/sample3.txt')

Some points to remember:

  • If there was already a file at with that name, then it will be silently overwritten.
  • If any of the intermediate directory in destination path doesn’t exists then it will cause error.

Move all files in a directory to an another directory recursively

Suppose we want to move all the files in a directory to another directory. For that we need to iterate over all the files in source directory and move each file to destination directory using shutil.move() i.e.

import shutil, os, glob

def moveAllFilesinDir(srcDir, dstDir):
    # Check if both the are directories
    if os.path.isdir(srcDir) and os.path.isdir(dstDir) :
        # Iterate over all the files in source directory
        for filePath in glob.glob(srcDir + '\*'):
            # Move each file to destination Directory
            shutil.move(filePath, dstDir);
    else:
        print("srcDir & dstDir should be Directories")

Let’s use this to move all files in boost_1_66 to boost_1_66_backup i.e.

sourceDir = '/home/abc/lib/Boost/boost_1_66'
destDir =  '/home/abc/lib/Boost/boost_1_66_backup'
    
moveAllFilesinDir(sourceDir,destDir)

Move file and Create Intermediate directories

As we know that shutil.move() will give error if any of the intermediate directory is not present then it will give error. So, let’s create a function that will move the file to destination directory and will also create all directories in the given path i.e.

import shutil, os, glob

def moveAndCreateDir(sourcePath, dstDir):
    if os.path.isdir(dstDir) == False:
        os.makedirs(dstDir); 
    shutil.move(sourcePath, dstDir);

Let’s use this to move a file to a path that don’t exists i.e.

sourceFile = 'test/sample1.txt'
destDir =  'test/test22/test1'

moveAndCreateDir(sourceFile, destDir)

Move symbolic links

In case source file path i.e. src is a symbolic link then at destination path a link will be created that will point to target of source link. Also source link will be deleted.

Move a directory to an another directory

We can also move a complete directory to another location i.e.

sourceDir = 'test3'
destDir =  'test'

shutil.move(sourceDir, destDir)

Some points :

  • If destination directory exists then source directory will be moved inside that.
  • If destination directory doesn’t exists then it will be created.
  • If any intermediate directory doesn’t exists i.e. path is not valid then it can cause error.
  • If destination directory already contains an another directory with same name as source directory then it will cause error.

Complete example is as follows,

import shutil, os, glob

def moveAndCreateDir(sourcePath, dstDir):
    # Check if dst path exists
    if os.path.isdir(dstDir) == False:
        # Create all the dierctories in the given path
        os.makedirs(dstDir); 
    # Move the file to path    
    shutil.move(sourcePath, dstDir);
            


def moveAllFilesinDir(srcDir, dstDir):
    print(srcDir)
    print(dstDir)
    # Check if both the are directories
    if os.path.isdir(srcDir) and os.path.isdir(dstDir) :
        # Iterate over all the files in source directory
        for filePath in glob.glob(srcDir + '/*'):
            # Move each file to destination Directory
            print(filePath)
            shutil.move(filePath, dstDir);
    else:
        print("srcDir & dstDir should be Directories")        

def main():

    print("**** Move a file to another directory ****")    
    
    newPath = shutil.move('sample1.txt', 'test')    
    
    print(newPath) 
    
    #newPath = shutil.move('sample1.txt', 'test3/test/')    
    
    #print(newPath)
    
    print("**** Move a file to another location with new name ****")   
    
    newPath = shutil.move('sample2.txt', 'test/sample3.txt')
    
    print(newPath)
    
    
    sourceDir = '/home/varun/Documents/Boost/boost_1_66'
    destDir =  '/home/varun/Documents/Boost/boost_1_66_backup'
    
    moveAllFilesinDir(sourceDir, destDir)
    
    
    sourceFile = 'test/sample1.txt'
    destDir =  'test/test22/test1'
    
    moveAndCreateDir(sourceFile, destDir)
    
    
    sourceDir = 'test3'
    destDir =  'test'
    
    shutil.move(sourceDir, destDir)
    
if __name__ == '__main__':
    main()

 

 

1 thought on “Python : How to move files and Directories ?”

  1. hi could you please suggest me code for below requirememnt.

    i have directory with no of file those entire folder i have to load into s3 bucket
    could you plz help on this.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top