RPA / Robocorp
Files and folders / Move and rename
Move/rename a single file/folder
tasks.py
from robocorp.tasks import task
import shutil
@task
def files_or_folders_move_rename_single():
source = "my-file.txt"
destination = "my-folder/my-file-renamed.txt" # This can be either a file or a folder
shutil.move(source, destination)
Move/rename multiple files/folders
tasks.py
from robocorp.tasks import task
import shutil
import os
@task
def files_or_folders_move_rename_multiple():
# List of source and destination paths as tuples
paths_to_move = [
("my-file.txt", "my-folder/my-file-renamed.txt"),
("my-folder", "backup-folder/my-folder-renamed")
]
for source, destination in paths_to_move:
try:
# Check if the source file or folder exists
if not os.path.exists(source):
print(f"Source '{source}' does not exist. Skipping...")
continue
# Create destination folder if it doesn't exist (only for folder destinations)
dest_dir = os.path.dirname(destination) if not os.path.isdir(destination) else destination
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
print(f"Destination folder '{dest_dir}' created.")
# Move the source file/folder to the destination
shutil.move(source, destination)
print(f"'{source}' has been moved to '{destination}' successfully.")
except Exception as e:
print(f"An error occurred while moving '{source}' to '{destination}': {e}")