How to Move a File in Python

File management is an essential task for every software developer, and moving files from one location to another is one of the common operations.

Python provides several built-in functions and modules to perform this task efficiently.

In this tutorial, we’ll explore how to move a file in Python using the shutil module.


The shutil Module

The shutil module provides a set of high-level operations on files and collections of files.

It is a useful tool for file management operations, including moving files.

The module provides the shutil.move function to move a file from one location to another.

Syntax

The syntax of the shutil.move function is as follows:

shutil.move(src, dst, *, src_dir_fd=None, dst_dir_fd=None)

Where:

  • src is the source file path.
  • dst is the destination file path.
  • src_dir_fd is an optional parameter that represents the file descriptor of the source directory.
  • dst_dir_fd is an optional parameter that represents the file descriptor of the destination directory.

Code Example

Here’s a code example of how to use the shutil.move function to move a file in Python:

import shutil

src = '/path/to/source/file.txt'
dst = '/path/to/destination/file.txt'

shutil.move(src, dst)

In the code example above, we imported the shutil module and defined the source and destination paths.

Then, we used the shutil.move function to move the file from the source to the destination.

Moving Directories

The shutil.move function can also be used to move directories.

If the destination path already exists, the source directory will be moved inside the destination directory.

If the destination path does not exist, the source directory will be renamed to the destination path.

Code Example

Here’s a code example of how to use the shutil.move function to move a directory in Python:

import shutil

src = '/path/to/source/directory'
dst = '/path/to/destination/directory'

shutil.move(src, dst)

In the code example above, we imported the shutil module and defined the source and destination paths.

Then, we used the shutil.move function to move the directory from the source to the destination.


Conclusion

Moving files and directories is an essential task in software development. Python provides the shutil module to perform this task efficiently.

The shutil.move function is a useful tool to move files and directories from one location to another.

We hope this post has provided you with a comprehensive guide to moving files in Python using the shutil module.