4
\$\begingroup\$

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)
\$\endgroup\$
  • \$\begingroup\$ The only problem I found with your script is that you shouldn't name your variable dir as it is the name of a global function. \$\endgroup\$ – rahmu Sep 21 '12 at 14:39
1
\$\begingroup\$

What if the script renames file "a.zip" to "b.zip", and both files "a.zip" and "b.zip" exist in the same directory?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.