def renameFilesInDir( dir_name ):
    """
    given a directory
    rename all the files therein with the pattern:
    dir_name_nnnn
    where nnnn is a unique number (just count up from 1)
    NOTE: the file extension is preserved!
    NOTE: it does not recurse through sub directories!!
    """
    i = 1   # index used to create unique name in directory

    print 'dir_name is: ', dir_name

    for f in os.listdir( dir_name):

        print 'file: ', f, '--',
        
        if os.path.isdir(f):
            print 'skipping'
            continue

        # if, for example, dir_name is: "d:\pictures\2008\2008_11_01_family"
        # f, at this point, is d:\pictures\2008\2008_11_01_family\img0001.jpg
        # dir_basename needs to be 2008_11_01_family
        # then we rename f to be 2008_11_01_family_0001.jpg (in that same dir)

        froot, ext = os.path.splitext(f)        #get the extension
        # (froot is d:\pictures\2008\2008_11_01_family\img0001)
        # (ext is jpg)

        if ext.lower() != '.jpg':
            print 'skipping'
            continue                # we only work on JPEGs

        dir_root, fname = os.path.split(froot)  #get the dir and base names
        # (dir_root is d:\pictures\2008\2008_11_01_family)
        # (fname is img0001)

        dir_basename = os.path.basename( dir_name)
        # (dir_basename is 2008_11_01_family) <= that's the one I really want!

        new_base = dir_basename + str.format('{i:04}',i=i) + ext
        new_name = os.path.join(dir_name, new_base)
        # uses the new string formatting, to generate the "0001" numbering

        file_to_rename = os.path.join(dir_name, f)

        print 'Renaming %s to %s.' % (f,new_base)
        os.rename(file_to_rename, new_name)
        
        i += 1      # 1 becomes 2, etc.

        # that should do it.

    given a directory
    rename all the files therein with the pattern:
    dir_name_nnnn
    where nnnn is a unique number (just count up from 1)
    NOTE: the file extension is preserved!
    NOTE: it does not recurse through sub directories!!
    
recipes/Python/576597_Directory_Walking_File_Renamer/recipe-576597.py