Monday, September 15, 2008

oh the power of python, I try to use it whenever possible since I hate it to be stuck with just java...

a simple program to find all files containing a space at a certain position and to rename it to the correct name needed for my system:

#!/usr/bin/python

import re, os

rxin = '.*bsksa.* _[0-9].txt'
foo = re.compile(rxin)

for fname in os.listdir(os.getcwd()):
allowed_name = re.compile(rxin).match

if allowed_name(fname):
os.rename(fname,fname.replace(' ',''))


or short, find files and replace spaces with nothing. The reg expression just filters the data.

3 comments:

Keith Bradnam said...

Python looks very strange when you are not used to it.

My perl script equivalent (sort of):

#!/usr/bin/perl
#
# Usage: rename.pl perlexpr [files]

($regexp = shift @ARGV) || die "Usage: rename.pl perlexpr [filenames]\n";

if (!@ARGV) {
@ARGV = < STDIN >;
chomp(@ARGV);
}


foreach $_ (@ARGV) {
$old_name = $_;
eval $regexp;
die $@ if $@;
rename($old_name, $_) unless $old_name eq $_;
}

Gert Wohlgemuth said...

now this looks even stranger :P

well I used to work so much with perl and this example convince me once more that I stay away from it. I know what it does and how it works, but it just looks so ugly :)

Keith Bradnam said...

Ugly?? I was thinking exactly the same thing about your python example! :-)