Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 238
Alex Lenail Avatar asked Oct 27 '18 23:10

Alex Lenail


People also ask

What does Pathlib path () do?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.

How can we create a directory with the Pathlib module?

Create Directory in Python Using the Path. mkdir() Method of the pathlib Module. The Path. mkdir() method, in Python 3.5 and above, takes the path as input and creates any missing directories of the path, including the parent directory if the parents flag is True .

How do I rename a file in Pathlib?

Path.rename(target) Rename this file or directory to the given target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object.

What is path () in Python?

PYTHONPATH is an environment variable which the user can set to add additional directories that the user wants Python to add to the sys. path directory list. In short, we can say that it is an environment variable that you set before running the Python interpreter.


2 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.

like image 65
jedwards Avatar answered Oct 10 '22 17:10

jedwards


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)
like image 43
Apalala Avatar answered Oct 10 '22 15:10

Apalala