Is there a quick way to replace part of the path in python?
for example:
old_path='/abc/dfg/ghi/f.txt'
I don't know the beginning of the path (/abc/dfg/
), so what I'd really like to tell python to keep everything that comes after /ghi/
(inclusive) and replace everything before /ghi/
with /jkl/mno/
:
>>> new_path
'/jkl/mno/ghi/f.txt/'
replace() method in Python is used to rename the file or directory. If destination is a directory, OSError will be raised. If the destination exists and is a file, it will be replaced without error if the action performing user has permission.
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.
Pure paths. Pure path objects provide path-handling operations which don't actually access a filesystem. There are three ways to access these classes, which we also call flavours: class pathlib. PurePath (*pathsegments)
basename to Find Filename From the File Path in Python. The first and the easiest way to extract part of the file path in Python is to use the os. path. basename() function.
If you're using Python 3.4+, or willing to install the backport, consider using pathlib
instead of os.path
:
path = pathlib.Path(old_path)
index = path.parts.index('ghi')
new_path = pathlib.Path('/jkl/mno').joinpath(*path.parts[index:])
If you just want to stick with the 2.7 or 3.3 stdlib, there's no direct way to do this, but you can get the equivalent of parts
by looping over os.path.split
. For example, keeping each path component until you find the first ghi
, and then tacking on the new prefix, will replace everything before the last ghi
(if you want to replace everything before the first ghi
, it's not hard to change things):
path = old_path
new_path = ''
while True:
path, base = os.path.split(path)
new_path = os.path.join(base, new_path)
if base == 'ghi':
break
new_path = os.path.join('/jkl/mno', new_path)
This is a bit clumsy, so you might want to consider writing a simple function that gives you a list or tuple of the path components, so you can just use find
, then join it all back together, as with the pathlib
version.
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