Tuesday, December 8, 2009

Time for Python Neenjah!

I happened upon an administrative assistant today who was renaming files using Windows Explorer. She had a folder with about 50 or so sub-folders, many of which contained sub-folders of their own. Every file needed to be renamed with the company name prefixing it. So for example, the file "january-charts.pdf" needed to be renamed to "Company - january-charts.pdf".

"You know", I said, "I could help that go a little faster if you're interested." I happened to know that these files needed to be sent as of yesterday, so I figured she wouldn't mind me helping to trim an hour or two off them getting out. That must mean it's time for Python Neenjah! (In case you missed it, that was a somewhat veiled reference to xkcd 'Regular Expressions')

A month or two ago I had put together a re-usable python module to allow easy recursively searching a directory. I know, I know, python already includes similar functionality. But it was weird to me, and I wanted a simpler and more flexible format. The module I built, inspire by some ideas I found around the internet, allows a callback to be specified whenever a file is found. It means you can do virtually anything from that directory search, and never really be concerned about how it does it.

from dirsearch import DirSearch

def search_callback(file):
print file

dir = DirSearch('C:\Path\Whatever', show_output=True)
dir.search(search_callback)

The source for dirsearch.py is included below.

Well with my module it only took a few lines of code to put together a command to complete the task at hand.

DirSearch.py


rrename.py

0 comments:

  © Blogger template 'Minimalist G' by Ourblogtemplates.com 2008

Back to TOP