Last active
March 19, 2020 20:53
-
-
Save kaspermunch/c9f10904c2a73ea0bbcb482cd1775916 to your computer and use it in GitHub Desktop.
Simple manipulation of paths
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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