def increment_filename(inpfile, ndigits=3, delim='.'):

    dirname, filename = os.path.split(inpfile)
    base, ext = os.path.splitext(filename)
    if ext == '':
        ext = '.000'

    if ext.startswith('.'):
        ext   = ext[1:]
    if ndigits < 3:
        ndigits = 3
    form  = "%%.%ii" % (ndigits)

    def _incr(base, ext):
        if ext.isdigit():
            ext = form % (int(ext)+1)
        else:
            found = False
            if '_' in base:
                parts = base.split('_')
                for iw, word in enumerate(parts[::-1]):
                    if word.isdigit():
                        parts[len(parts)-iw-1] = form % (int(word)+1)
                        found = True
                        break
                base = '_'.join(parts)
            if not found and '.' in base:
                parts = base.split('.')
                for iw, word in enumerate(parts[::-1]):
                    if word.isdigit():
                        parts[len(parts)-iw-1] = form % (int(word)+1)
                        found = True
                        break
                base = '.'.join(parts)
            if not found:
                base = "%s_001" % base
        return (base, ext)

    # increment once
    base, ext = _incr(base, ext)
    fout = pathOf(dirname, base, ext, delim=delim)

    # then gaurantee that file does not exist,
    # continuing to increment if necessary
    while (os.path.exists(fout)):
        base, ext = _incr(base, ext)
        fout = pathOf(dirname, base, ext, delim=delim)
    return fout
increment a data filename, returning a new (non-existing) filename
dataset/ETHPy150Open xraypy/xraylarch/plugins/io/fileutils.py/increment_filename