How to move a file or directory in Python
How to move a file or directory in Python.
Here's a step-by-step tutorial on how to move a file or directory in Python:
- Import the
shutil
module: First, you need to import theshutil
module, which provides functions for file operations.
import shutil
- Move a file to a different location: To move a file from one location to another, you can use the
shutil.move()
function. This function takes two arguments: the source file path and the destination file path.
source = '/path/to/source/file.txt'
destination = '/path/to/destination/file.txt'
shutil.move(source, destination)
In the above code, replace /path/to/source/file.txt
with the actual source file path and /path/to/destination/file.txt
with the desired destination file path.
- Rename a file: If you want to rename a file while moving it, you can simply provide the new filename as the destination path.
source = '/path/to/source/file.txt'
destination = '/path/to/destination/new_file.txt'
shutil.move(source, destination)
In this example, the source file will be moved to the destination directory with a new name new_file.txt
.
- Move a directory: To move an entire directory (including all its contents) to a new location, you can use the
shutil.move()
function in a similar way.
source_dir = '/path/to/source/directory'
destination_dir = '/path/to/destination/directory'
shutil.move(source_dir, destination_dir)
Replace /path/to/source/directory
with the path of the source directory, and /path/to/destination/directory
with the desired destination directory path.
- Handling exceptions: When moving files or directories, there can be various exceptions that may occur, such as permission errors or file not found errors. It's a good practice to handle these exceptions to provide feedback or perform alternative actions.
try:
shutil.move(source, destination)
print("File moved successfully!")
except FileNotFoundError:
print("Source file not found!")
except PermissionError:
print("Permission denied!")
In the above example, the code is wrapped in a try-except
block to catch specific exceptions. You can handle different exceptions depending on your requirements.
That's it! You now know how to move files and directories in Python using the shutil
module. Feel free to explore more functions and options available in the shutil
module for other file operations.