Replace part of path - python
Is there a quick way to replace part of a path in python?
eg:
old_path='/abc/dfg/ghi/f.txt'
I don't know the start of the path ( /abc/dfg/
), so I would like to tell python to keep whatever comes after /ghi/
(inclusive) and replaces everything before /ghi/
with /jkl/mno/
:
>>> new_path
'/jkl/mno/ghi/f.txt/'
source to share
If you are using Python 3.4+ or want to install a backport , consider using pathlib
instead 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 2.7 or 3.3 stdlib, there is no direct way to do this, but you can get the equivalent parts
by iterating over os.path.split
. For example, keeping each component of the path until you find the first one ghi
, and then adding a new prefix will replace everything before the last one 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 clunky, so you might want to write a simple function that gives you a list or tuple of path components, so you can just use find
and then concatenate everything like with pathlib
version.
source to share
>>> import os.path
>>> old_path='/abc/dfg/ghi/f.txt'
First select the relative path from the starting directory of your choice using os.path.relpath
>>> rel = os.path.relpath(old_path, '/abc/dfg/')
>>> rel
'ghi\\f.txt'
Then add a new first part of the path to that relative path using os.path.join
>>> new_path = os.path.join('jkl\mno', rel)
>>> new_path
'jkl\\mno\\ghi\\f.txt'
source to share
Pretty naive approach, but does the job:
Functions:
def replace_path(path, frm, to):
pre, match, post = s.rpartition(frm)
return ''.join((to if match else pre, match, post))
Example:
>>> replace_path(s, '/ghi/', '/jkl/mno')
'/jkl/mno/ghi/f.txt'
>>> replace_path(s, '/whatever/', '/jkl/mno')
'/abc/dfg/ghi/f.txt'
source to share