Move File in Python: A Complete Guide

Posted in /  

Move File in Python: A Complete Guide
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    Python comes with an inbuilt module, shutil that provides many methods for high-level file operations. It also provides a move() method that can move files and directories from one location to another on our computer. Often writing a program , we encounter situations where we wish to move files or directories from one location to another.

    For example, let's say we are creating a python program that reads multiple files, and based on the data on those files, we wish to move them into specific locations. Here the Python's shutil.move() comes in play. This inbuilt method allows us to move a file or directory from a specific location to another location in our system only, so we can move files and directories using the python program. And in this tutorial, we will discuss this method in detail, so let's get started.

    Python shutil module

    shutil is an inbuilt python module that offers myriad methods to manage files and directories in a system using the python programming language. Although different operating systems have different file management systems, but all those operating systems that support Python also support shutil, so we don't have to worry about the operating systems while working with shutil.

    Python move file

    With the shutil.move() method we can move files and directories within our computer system. The move() method can accept three arguments, where the first two arguments and mandatory and the third argument is optional.

    Syntax

    move(source, destination, copy_function = copy2)

    arguments source : It is a string value that represents the file or directory path that we want to move.

    destination: It is also a string value that represents the directory path where we want to move our file or directory.

    copy_function: It is an optional callback argument that accepts a function as an argument value. By default, its value is copy2 , which is also a method of shutil that can copy data as well as metadata of the file.

    The path value for the source and destination arguments can be absolute or relative. In the absolute path value, we specify the complete path from the root directory. In the relative path, we specify the path location from the directory where our Python file is located.

    Facts about shutil.move() method:

    • The shutil.move() method returns the destination path where the file is moved.
    • If the source file or directory already exists in the destination directory, the shutil.move() method would raise the "shutil.Error: Destination path already exists" error.
    • The shutil.move() method will use os.rename() method to move the file if the destination directory is the current working directory where the python file is located.

    Python Move file Examples

    Let's write some code in Python that can move files from one location to another.

    Move a file in Python

    Let's say we have downloaded a picture logo.png from the internet, and it is stored in our downloads directory, and we want to move it to our game folder directory with other game resources.

    import shutil
    
    # source file path with the full file name
    source = r'C:\Users\tsmehra\Downloads\logo.png'
    
    # destination path where we want to move the file
    destination = r'C:\Users\tsmehra\Desktop\code\game folder'
    
    # move the file
    print("The file has been moved to:" , shutil.move(source, destination))

    Output

    The file has been moved to: C:\Users\tsmehra\Desktop\code\game folder

    The above example will move the file logo.png from the source Downloads directory to the destination game folder directory. In this example, I have provided the absolute path of the source file and destination directory and also specified paths as a raw string by putting r as a prefix to both the strings. With raw string, we do not have to worry about escape characters in python, and wherever you provide an absolute path, I always suggest using raw string instead of a normal Python string.

    Move a file and change its name

    In the above example, we simply move the file from one location to another, and when we move it, the name of the file remains the same. But if we wish to change the file name when it is moved to the destination directory, we can append the new name to the destination path. And when the file is moved to the destination, its name will be changed to the new specified name.

    Example

    Suppose we have a picture.png file in our Downloads folder, and we want to move it to our game folder directory as snake-picture.png how would we do that?

    import shutil
    
    # source file path with the full file name
    source = r'C:\Users\tsmehra\Downloads\picture.png'
    
    # destination path and the new file name
    destination = r'C:\Users\tsmehra\Desktop\code\game folder\snake-picture.png'
    
    # move the file
    print("The file has been moved to:" , shutil.move(source, destination))

    Output

    The file has been moved to: C:\Users\tsmehra\Desktop\code\game folder\snake-picture.png
    

    Move Multiple file

    The shutil.move() method can only move one file at a time. If we wish to move multiple files, then we need to use a loop that iterates over multiple files and moves them to the specified location.

    Suppose we have multiple .txt and .pdf file in a directory, and we wish to move all the .txt files in the text directory and .pdf files to the document directory. For this, we first need to list out all the files present in the source directory, loop over them, check for the .txt and .pdf files and move them to specified directories. To list out all the files present in a directory, we can take the help of the os.listdir() method that returns a list of file names present in the directory.

    Example

    import shutil
    import os
    
    # source directory
    source = r'C:\Users\tsmehra\Downloads'
    
    # all files present in the source directory
    files = os.listdir(source)
    
    #pdf file destination directory
    pdf_destination = r'C:\Users\tsmehra\Desktop\code\documents'
    
    # text file destination directory
    txt_destination = r'C:\Users\tsmehra\Desktop\code\text'
    
    for file in files:
        # check for the txt file
        if file.endswith('.txt'):
            # move the .txt file
            shutil.move(rf'{source}\{file}', txt_destination)
            print("Moved txt file....")
    
        #check for pdf files
        if file.endswith('.pdf'):
            # move the .pdf file
            shutil.move(rf'{source}\{file}', pdf_destination)
            print("Moved pdf file....")
    

    Output

    Moved txt file....
    Moved pdf file....
    Moved txt file....

    Conclusion

    In this Python tutorial, we learned how to move files using the Python programming language. Python's shutil modules provide a move() method that allows us to move one file or directory from one location to another. With the move() method we can only move one file or directory at a time for moving multiple files or directories, we can take the help of loops.

    To know more about how to manage files in Python click here .

    People are also reading:

    Leave a Comment on this Post

    0 Comments