python 练习: 批量修改文件名


    #!/usr/bin/python
#author Fang lungang
# Created:  Fang lungang 02-19-2007
# Modified: Fang lungang 02-19-2007 12:31>
r"""
Name
    rnr - Re-Name files Regexp
Synopsis
    rnr [-vn] 'from_pattern' 'to_pattern'
Description
    rename files, -v for more verbose, -n for not execute the cmd realy
Note
    the from_pattern and to_pattern must be enclosed by single quotes
    ('), otherwise they'll be intercepted by shell.
Example:
    $ rnr.py -v  '*.ab*' '\1.py\2'
    (.*)\.ab(.*)
    mv more.ab more.py
    mv more.abc more.pyc
    mv rnr.abc rnr.pyc
    mv test.ab test.py
    mv test.abc test.pyc
"""
def rnr(src, dest, verbose = False, printOnly = False ):
    import glob, re, os
    # if printOnly, it's nonsense if not verbose
    if printOnly: verbose = True
    # translate shell style wildcards to regular expression with groups
    src_regexp = src.replace('.', r'\.').replace('*', '(.*)')
    src_regexp = src_regexp.replace('?', '(.|)')
    src_regexp = src_regexp.replace('[', '([').replace(']', '])')
    if verbose: print src_regexp
    src_ro = re.compile(src_regexp)
    files = glob.glob (src)
    for afile in files:
        cmd = 'mv ' + afile + ' ' + src_ro.match(afile).expand(dest)
        if verbose: print cmd
        if not printOnly: os.system(cmd)
if __name__ == '__main__':
    import sys, getopt
    try:
        if sys.version.split()[0] >= '2.5':
            options, args = getopt.gnu_getopt(sys.argv[1:], 'nv')
        else:
            options, args = getopt.getopt(sys.argv[1:], 'nv')
    except getopt.GetoptError:
        print  __doc__
        sys.exit (-1)
    verbose = False
    printOnly = False
    for (o, v) in options:
        if o == '-v':
            verbose = True
        elif o == '-n':
            printOnly = True
    if len (args) != 2:
        print __doc__
        sys.exit (-2)
    else:
        rnr(args[0], args[1], verbose, printOnly)