move a directory in python

To move a directory in Python, you can use the shutil module that provides an easy way to move files and directories recursively.

Here's an example code snippet that moves a directory from the source directory to the destination directory:

main.py
import shutil
import os

src_dir = '/path/to/source/directory'
dst_dir = '/path/to/destination/directory'

try:
    shutil.move(src_dir, dst_dir)
    print(f"Directory '{src_dir}' moved to '{dst_dir}' successfully!")
except Exception as e:
    print(f"Error while moving directory: {e}")
288 chars
12 lines

In this code, we first import the shutil and os modules. We then define the paths of the source directory and the destination directory.

Next, we use the try-except block to catch any errors that may arise during the directory move process. Within the try block, we use the shutil.move() method to move the source directory to the destination directory. If the move is successful, we print a success message. If there's an error, we catch it and print an error message.

Note that the shutil.move() method will move the entire directory tree recursively, including all subdirectories and files.

related categories

gistlibby LogSnag