I have two utility functions that either append or remove a pattern onto a set of items within a directory. The functionality is exactly the same apart from the line that does the renaming which makes me believe I can merge them into one function.
Here are the two functions:
def append_items(source, pattern, dirs = True, recurse = False):
"""
Append the pattern to all items within a directory
source = act on this directory
pattern = add this to the start of the file
dirs = apply to directorys
recurse = work recursively
"""
for item in os.listdir(source):
path = os.path.join(source, item)
if "svn" not in item:
if os.path.isdir(path):
# Recurse first
if recurse:
append_items(path, pattern, dirs, recurse)
if dirs:
rename(path, path + pattern)
elif os.path.isfile(path):
name, ext = os.path.splitext(item)
# Append pattern, add extension back
new_path = os.path.join(source, "%s%s" % (name, pattern) + ext)
rename(path, new_path)
#----------------------------------------------------------------------------------------------------------
def remove_string_from_items(source, pattern, dirs = True, recurse = False):
"""
Remove a pattern from all items within a directory
source = directory
pattern = text to replace
"""
for item in os.listdir(source):
path = os.path.join(source, item)
if "svn" not in item:
if os.path.isdir(path):
# Recurse first
if recurse:
remove_string_from_items(path, pattern, dirs, recurse)
if dirs and pattern in item:
target = os.path.join(source, string.replace(item, pattern, ""))
rename(path, target)
elif os.path.isfile(path) and pattern in item:
target = os.path.join(source, string.replace(item, pattern, ""))
rename(path, target)
Can anybody point me towards a cleaner solution?
The following should be equivalent to what you have, with less repeated code: