regular expressions and renaming files

François Pinard pinard at iro.umontreal.ca
Wed Feb 18 17:01:14 EST 2004


[David Lebel]

> One script I had in my toolbox was used to rename files using a
> regular expression.  That script came from Tom Christiansen (of Perl
> fame) and shows the great flexibility of Perl doing regular expression
> operations.  Now, I don't know where to start doing the conversion.

Here is my cut of it, from my personal toolbox (so the French comments).
I submit it here in case people would suggest improvements... :-)


#!/usr/bin/env python
# -*- coding: Latin-1 -*-
# François Pinard <pinard at iro.umontreal.ca>, 1991, 2004.
# D'après Tom Christiansen <tchrist at convex.com>, alt.sources 1990-12-08.

"""\
Renommer les fichiers selon un thème de transformation fourni.

Usage: rename [OPTION]... TRANSFORMATION FICHIER...

Options:
    -v   Décrire les changements effectués.

TRANSFORMATION doit être, soit une expression Python qui évalue le
nouveau nom pour le fichier dont le nom est fourni initialement dans
`_', soit un énoncé Python qui affecte à la variable `_' le nouveau nom
pour le fichier dont le nom est initialement contenu dans `_'.

On peut compter sur les modules `os', `re' et `sys'.

Exemples:
    rename '_[:-5]' *.orig
    rename -v 'if not _.startswith("Make"): _ = _.lower()' *
    rename '_ + ".bad"' *.f
    rename 'if _[0] in "yY": print _; _ = _.replace("foo", "bar")' *
"""

import os, re, sys

def main(*arguments):
    if not arguments:
        sys.stdout.write(__doc__)
        raise SystemExit
    assert len(arguments) < 2, arguments
    verbeux = False
    import getopt
    options, arguments = getopt.getopt(arguments, 'v')
    for option, valeur in options:
        if option == '-v':
            verbeux = True
    operation = arguments[0]
    for argument in arguments[1:]:
        _ = argument
        try:
            _ = eval(operation)
        except SyntaxError:
            exec operation
        if _ != argument:
            try:
                os.rename(argument, _)
            except IOError, diagnostic:
                sys.stderr.write('* %s: %s\n' % (argument, diagnostic))
            else:
                if verbeux:
                    sys.stderr.write('%s -> %s\n' % (argument, _))

if __name__ == '__main__':
    main(*sys.argv[1:])

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list