Simplest way to clobber/replace one populated directory with another?

Travis Griggs travisgriggs at gmail.com
Tue May 15 12:37:30 EDT 2018


I have a directory structure that might look something like:

    Data
        Current
            A
            B 
            C 
        Previous
            A 
            X

In as simple/quick a step as possible, I want to rename Current as Previous including the contents and wiping out the original such that it is now:

    Data
        Previous
            A
            B
            C

I've tried something like:

    from pathlib import Path
    src = Path('Data/Current’)
    dest = Path('Data/Previous’)
    src.replace(dest)

The docs led me to hope this would work:

    "If target points to an existing file or directory, it will be unconditionally replaced.”

But it *does* appear to be conditional. I get a "Directory not empty" exception. I guess I could recursively delete the ‘Previous' directory first. Is that basically the only solution? Or is there a better way to achieve this?

(I prefer `pathlib`, but if `os` or `shutil` is the better hammer here, I'm not opposed to them)

(I am running on Linux)


More information about the Python-list mailing list