More Python posts
October 29, 2002
I know this is getting silly

Another round of renaming scripts. This time I've tried to provide "functional" and "imperative" styles for Python and Perl. For this sort of problem I personally think of it as a problem of processing a list of names so I prefer the functional approach. If the end result were to be a list of some sort then I think the functional approaches win hands down. The presence of the rename "side effect" means that they're not pure but The Python imperative style is courtesy of Jarno Virtanen with a downgrade by me so it matches the functionality of the others.

As a Python script, functional style:

import glob
import os

map(lambda f: os.rename(f + '.txt', f + '.xml'),
    [os.path.splitext(f)[0] for f in glob.glob('*.txt')])

As a Python script, imperative style:

import glob
import os

for filename in glob.glob('*.txt'):
    base = os.path.splitext(filename)[0]
    newname = '%s.%s' % (base, 'xml')
    os.rename(base + '.txt', newname)

As a Perl script, functional style:

map(rename($_ . '.txt', $_ . '.xml'),
    map(s/\.txt$//, glob('*.txt')))

As a Perl script, imperative style:

foreach $f (glob('*.txt')) {
    $f =~ s/\.txt$//;
    rename($f . '.txt', $f . '.xml');
}

Finally the shortest solution, provided by John Masson. As a Bash shell script from the command line:

for i in *.txt; do mv $i ${i%%.txt}.xml; done
Posted by Alex at October 29, 2002 01:52 PM
Comments
Now all we need is a canonical Java version. ;-) Posted by: Jarno Virtanen on October 29, 2002 11:05 PM
I'll give it a go :) Posted by: Alex on October 30, 2002 06:47 AM
using windows shell: ren *.txt *.xml is even shorter and simpler, the Bash thing is obfuscated with % and ; and %% and $ thingies. Posted by: Will Stuyvesant on November 2, 2002 02:05 PM
Unix has the rename command as well. rename .txt .xml ./* Posted by: asdf on December 15, 2002 02:14 PM
Post a comment
Name:


Email Address:


URL:


Comments:


Remember info?