Way for Pathlib Path.rename() to create intermediate directories?

Viewed 4254

I'm trying to move some files around on my filesystem. I'd like to use Python 3's Pathlib to do so, in particular, Path.rename.

Say I want to move Path('/a/b/c/d') to Path('/w/x/y/z').

Path('/a/b/c/d').rename(Path('/w/x/y/z'))

gives

FileNotFoundError: [Errno 2] No such file or directory: '/a/b/c/d' -> '/w/x/y/z'

I can fix this with

os.makedirs(Path('/w/x/y', exist_ok=True)
Path('/a/b/c/d').rename(Path('/w/x/y/z'))

But that's less elegant than old school os, which has a method called renames which does this for you. Is there a way to do this in Pathlib?

3 Answers

It's not ideal, but something like the following would work

from pathlib import Path

def ensure(path):
    path.parent.mkdir(parents=True, exist_ok=True)
    return path

Path('a/b/c/before.txt').rename(ensure(Path('x/y/z/moved.txt')))

Pathlib.Path.mkdir doesn't return anything, so it seems like some sort of wrapper like this is necessary.

pathlib.Path.mkdir() is available:

newname = Path('/w/x/y/z')
newname.parent.mkdir(parents=True, exist_ok=True)
Path('/a/b/c/d').rename(newname)

Pathlib.mkdir offers the same parent-creation behavior

Pathlib.rename does not create parents, similar to how rename() does not create parents

Related