Newbie Question: Shell-like Scripting in Python?

Alex Martelli aleax at aleax.it
Wed Oct 2 04:01:36 EDT 2002


Mark McEahern wrote:

>> I want to rename files matching foo.* to be bar.*.  Ideally, I'd
>> like to be
>> able to say something like this:
>>
>>   rename foo.* bar.*
> 
> import glob
> import os
> for oldfile in glob.glob("foo.*"):
>     newfile = oldfile.replace("foo", "bar")
>     os.rename(oldfile, newfile)

Dangerous: this will rename foo.bafoope to bar.babarpe, which is
probably not what the original poster intended (at least, it's
not what such a "rename"-like command would do e.g. in DOS).

>>> 'foo.bafoope'.replace('foo','bar')
'bar.babarpe'
>>> 'foo.bafoope'.replace('foo','bar',1)
'bar.bafoope'
>>>

The 1 trailing argument to the replace method limits the number
of replacements to a maximum of 1, which is most likely what
is wanted here.

There are other issues: this will fail after renaming an
unknown subset of the 'foo.*' files, if one renaming fails,
e.g. because originally both a (say) 'foo.plik' and 'bar.plik'
exist.  One way around this would be to embed the call to
os.rename into a try/except statememt's try clause, so as
to be able to handle errors more "softly":

    try:
        os.rename(oldfile, newfile)
    except OSError, err:
        print "Cant rename %s -> %%s: %s" % (
            oldfile, newfile, err)



Alex




More information about the Python-list mailing list