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)
Ron Klein
1,20711 silver badges19 bronze badges
asked Sep 21, 2012 at 13:08
\$\endgroup\$
1
  • \$\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\$ Commented Sep 21, 2012 at 14:39

1 Answer 1

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?

answered Sep 22, 2012 at 21:45
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.