Simplest way to clobber/replace one populated directory with another?
Cameron Simpson
cs at cskk.id.au
Wed May 16 18:54:49 EDT 2018
On 15May2018 09:37, Travis Griggs <travisgriggs at gmail.com> wrote:
>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?
When I do this and want speed I go:
1) rename Previous to a scratch name (eg .rmtmp-$$-Previous; the mkstemp
function will help pick a free name for you). Make sure it is in the same
directory i.e. rename blah/blah/Previous to blah/blah/.rmtmp-$$-Previous) -
avoids accidentally crossing filesystem boundaries.
2) rename Current to previous
3) remove the old previous (I do this asynchronously in shell scripts)
In fact I do this so often in the shell that I have a trite script called "rmr"
that does 1+3, and routinely type:
rmr Previous && mv Current Previous
Prompt back instantly, "rm" of the temp name proceeding siletnly in the
background.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list
mailing list