📜 Rename Files by Natural Number Sorting in Python 2.7

April 8, 2015  Rename Files by Natural Number Sorting in Python 2.7

I needed to rename a bunch of files in natural sorting (e.g. FILENAME1 – FILENAME999), but needed the preceding zeroes such that file systems would read them in a natural order. This script will rename all files of the same name with a substituted filename string which are ordered 001, 002, 003 –> Infinite. If you have >999 filenames, change zfill(2) to the corresponding number of zeroes required.

#renames all files in a directory Participant Data X except for script itself
# ---------------------------------------------------------
# natsort.py: Natural string sorting.
# ---------------------------------------------------------
# http://code.activestate.com/recipes/285264/
# Adapted from Seo Sanghyeon.  Some changes by Connelly Barnes.
# This specific script adapted by Micah Wilson

import os

def try_int(s):
    "Convert to integer if possible."
    try: return int(s)
    except: return s

def natsort_key(s):
    "Used internally to get a tuple by which s is sorted."
    import re
    return map(try_int, re.findall(r'(d+|D+)', s))

def natcmp(a, b):
    "Natural string comparison, case sensitive."
    return cmp(natsort_key(a), natsort_key(b))

def natcasecmp(a, b):
    "Natural string comparison, ignores case."
    return natcmp(a.lower(), b.lower())

def natsort(seq, cmp=natcmp):
    "In-place natural string sort."
    seq.sort(cmp)
    
def natsorted(seq, cmp=natcmp):
    "Returns a copy of seq, sorted by natural string sort."
    import copy
    temp = copy.copy(seq)
    natsort(temp, cmp)
    return temp

# Example 
files = os.listdir('.')
natsort(files)
index = 0
for filename in files:
    if filename.startswith("filenamedescription"):
        os.rename(filename, 'NewFilename'+' '+str(index).zfill(2))
        index += 1

For usage, change the file name starting variable in filenamedescription. If you require a more advanced filename search, I suggest using re.search or similar regex packages.