How To Move A File In Python

In this blog post, we will learn how to move a file from one location to another using Python. This can be helpful when you want to organize your files or when you need to perform a specific action after moving a file to a new location.

Using the shutil module

Python provides a built-in module called shutil that comes with many high-level file operations. In this post, we will use the move() function available in the shutil module to move a file.

import shutil

source = 'path/to/source/file.txt'
destination = 'path/to/destination/folder'

shutil.move(source, destination)

In the above code snippet, source is the path to the file you want to move, and destination is the path to the folder where you want to move the file. The move() function will move the file from the source to the destination.

Note that if a file with the same name already exists in the destination folder, the existing file will be overwritten by the moved file.

Handling exceptions

It’s always good practice to handle exceptions while working with file operations. The shutil.move() function can raise the following exceptions:

  • shutil.Error: This exception occurs when the source and destination are the same, or when the destination is a subdirectory of the source.
  • FileNotFoundError: This exception occurs when the source file does not exist.
  • PermissionError: This exception occurs when you do not have permission to access the source or destination path.

Here’s an example of handling these exceptions:

import shutil

source = 'path/to/source/file.txt'
destination = 'path/to/destination/folder'

try:
    shutil.move(source, destination)
except shutil.Error as e:
    print(f"Error: {e}")
except FileNotFoundError as e:
    print(f"Error: {e}")
except PermissionError as e:
    print(f"Error: {e}")

In the above code, we have wrapped the move() function in a try-except block, and we catch various exceptions that might occur during the file moving operation. This way, you can provide proper error messages and handle any issues that might arise during the process.

Conclusion

In this blog post, we learned how to move a file from one location to another using Python’s built-in shutil module. We also discussed how to handle exceptions that may occur during the file moving operation. This knowledge will come in handy when working with file operations and organizing files in your Python projects.