Python file renaming tool implementation code. The code is as follows:
# Filename: brn. py
# Description: batch replace certain words in file names
# Use to bat rename the file in a dir (modify the suffix from a to B) for Windows Vista OS
Import sys
Import OS
Import fnmatch
Import re
# Parse params
P = input ("Please input work directory (current path for enter ):")
If p = '\ r ':
P = '.'
P = p. rstrip ('\ r ')
Print (p)
While not OS. path. exists (p ):
Print (p + 'is not existed. Please input the work directory :')
P = input ("Please input work directory (current path for enter ):")
S = input ("Please enter the words which need be modified (must ):")
While s = '\ r ':
S = input ("Please enter the words which need be replaced (must ):")
S = s. rstrip ('\ r ')
D = input ("Please enter the words which want to change to (must ):")
While d = '\ r ':
D = input ("Please enter the words which want to change to (must ):")
D = d. rstrip ('\ r ')
Try:
Sure = input ("Are you sure to rename the file named *" + s + "*" + "to *" + d + "*" + "in directory" + p + "? Y/n :")
Sure = sure. rstrip ('\ r ')
If sure! = 'Y ':
Print ("Cancel ")
Else:
For root, dirs, files in OS. walk (p, True ):
For file in files:
Print (OS. path. join (root, file ))
If OS. path. isfile (OS. path. join (root, file): # Only file is file, not a dir, do this
If fnmatch. fnmatch (file, '*' + s + '*'):
F = str (file). replace (s, d)
If p = '.':
Command = 'move '+ str (file) + "" + f
Else:
Command = "move" + OS. path. join (root, file) + "" + OS. path. join (root, f)
Print (command)
If OS. system (command) = 0: # do actual rename
Print ("Rename" + str (file) + "to" + f + "success ")
Else:
Print ("Rename" + str (file) + "to" + f + "failed ")
# Else:
# Print str (file) + "is a directory. omit"
Failed T IndexError:
Print (IndexError. message)