5

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)

Travis Griggs
  • 18,930
  • 17
  • 76
  • 137
  • I think the only way to go here is to first remove the dst if it exists. shutil.rmtree() seems like a reasonable hammer in this case. This question is possibly a duplicate of this: https://stackoverflow.com/a/11660641/3776268 – sehafoc May 15 '18 at 17:32

1 Answers1

0

Continuing from sehafoc's comment, after removing the entire file tree for dest ("Data/Previous") using shutil this way:

shutil.rmtree(dest)

Rename src ("Data/Current") to dest .

src.rename(dest)
Oluwafemi Sule
  • 27,776
  • 1
  • 40
  • 64