Skip to content

Instantly share code, notes, and snippets.

@kaspermunch
Last active March 19, 2020 20:53
Show Gist options
  • Save kaspermunch/c9f10904c2a73ea0bbcb482cd1775916 to your computer and use it in GitHub Desktop.
Save kaspermunch/c9f10904c2a73ea0bbcb482cd1775916 to your computer and use it in GitHub Desktop.
Simple manipulation of paths
import os, re
def modpath(p, parent=None, base=None, suffix=None):
par, name = os.path.split(p)
name_no_suffix, suf = os.path.splitext(name)
if type(suffix) is str:
suf = suffix
if parent is not None:
par = parent
if base is not None:
name_no_suffix = base
new_path = os.path.join(par, name_no_suffix + suf)
if type(suffix) is tuple:
assert len(suffix) == 2
new_path, nsubs = re.subn(r'{}$'.format(suffix[0]), suffix[1], new_path)
assert nsubs == 1, nsubs
return new_path
path = '/some/folder/myfile.suffix'
print(modpath(path, base='othername'))
print(modpath(path, parent='/banana/apple', suffix='.orange'))
print(modpath(path, parent='/banana/apple', suffix=''))
path = '/some/folder/myfile.suffix.othersuffix'
print(modpath(path, suffix='.orange'))
print(modpath(path, suffix=('.suffix.othersuffix', '.orange')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment