You compute the dirname twice.  Are you sure you don't want to use path.py?