这是第三个版本加入了参数选项
#!/usr/bin/python2
#auth:codewalker
#mail:001@codewalker.me
version = 0.3
from sys import argv, exit
from os import rename, listdir, getcwd
import re
import getopt
def usage():
print “USAGE:%s oldpart newpart” % argv[0]
print ‘’’
-v|–verbose verbose
-V|–version show version
-h|–help show this
‘’’
def main():
try:
opts, args = getopt.getopt(argv[1:], “hvV”, [“help”, “verbose”,”version”])
except getopt.GetoptError, e:
print e
usage()
exit(1)
is_output = False
is_verbose = False
is_show_version = False
for o, a in opts:
if o in ("-v", "--verbose"):
is_verbose = True
elif o in ("-h", "--help"):
usage()
exit()
elif o in ("-V", "--version"):
print 'version: %s' % version
exit()
else:
assert False, "option error"
exit(1)
if len(args) == 2:
try:
files = listdir(getcwd())
for old\_file\_name in files:
if args\[0\] in old\_file\_name:
new\_file\_name = re.sub(args\[0\],args\[1\],old\_file\_name)
#rename(old\_file\_name,new\_file\_name) #change names
if is_verbose:
print '%s => %s' % (old\_file\_name, new\_file\_name)
except OSError,e:
print e
else: print "DONE"
else:
usage()
exit(1)
if __name__ == ‘__main__‘:
main()