Home‎ > ‎Personal‎ > ‎on my mind‎ > ‎

Bit by the Python

posted Jul 2, 2010, 8:14 AM by Matt Francis
While I'm an electrical engineer by training, I've always gravitated towards programming and languages.  Don't get me wrong, I enjoy hardware and circuit design, but a good bit of programming can be just as gratifying as a functioning circuit.  One of my favorite "utility" languages is Python.  It has an elegant syntax and, while a bit verbose, when I come back to a bit of code months or years later, I quickly understand how it works, even if it has 0 comments;  I can't really say the same for C or the devil's own Perl.

Here's an example of something that hurts my brain to remember how to do in a shell language, like Bash or Csh, but took literally less than a minute to do in Python.  Goal: give every directory in a sub-directory a prefix:

import os


for f in files:
    if os.path.isdir(f):
       cmd="mv %s %s%s" % (f,PREFIX, f)

#NOTE: alternatively, concatenation works too!: cmd="mv "+f+" "+PREFIX+f

One of the truly powerful features of python are all of the libraries it comes with.  Here, I'm using the "OS" module to query for directories and to run system commands.  There are even better ways to do this, but this gets the job done!