Python

<< Back to wiki homepage

My crappy python snippets that I don't want to re-remember

Table of contents:

Move files recursively

def movetree(src, dst):
    """Moves everything from src folder into dst folder recursively

    :param: src: Source folder, str
    :param: dst: destination folder, str
    """

    for item in os.listdir(src):
        source_file = os.path.join(src, item)
        dest_file = os.path.join(dst, item)
        if os.path.isdir(source_file):
            # Ensure folder exists on the destination too
            if not os.path.exists(dest_file):
                os.mkdir(dest_file)
                # Copy the user/group info
                source_stat = os.stat(source_file)
                os.chown(
                    dest_file,
                    source_stat[ST_UID],
                    source_stat[ST_GID]
                )

            # We can recurse the function now for this folder
            movetree(source_file, dest_file)
        else:
            if os.path.exists(dest_file):
                # Already exists on destination, remove from source
                os.remove(source_file)
                continue

            # Move the file
            move(source_file, dest_file)