I'm quite new to Python and would love to gather feedback on my code. I've written a piece a script that allows me to search all file or directory names within a folder matching a particular pattern. The caller can specify if the function should be recursive or not.
It's only a basic script I would love to know how it could be improved!
import sys
import os
import string
def rename(source, pattern, replacement, dirs = False, recurse = False):
"""
Rename a file or directory
source = source directory
pattern = old string
replacement = new string
dirs = apply to directorys
recurse = move recursivley
"""
dir = os.path.abspath(source)
for item in os.listdir(dir):
# Get the full path
item = os.path.join(source, item)
if os.path.isfile(item) and pattern in item:
os.rename(item, string.replace(item, pattern, replacement))
elif os.path.isdir(item):
if recurse:
# Move to the next level, before renaming
rename_items(item, pattern, replacement, dirs, recurse)
if pattern in item and dirs:
os.rename(item, string.replace(item, pattern, replacement))
if __name__ == '__main__':
source = sys.argv[1]
pattern = sys.argv[2]
replacement = sys.argv[3]
rename(source, pattern, replacement, True, True)
dir
as it is the name of a global function. \$\endgroup\$