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?
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.
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 .
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With