I am trying to rename my files incrementally with a counter starting at 1, which process them in a way depending on their prefix and same file extension. The directory has the following files examples:
BS - foo.fxp
BS - bar.fxp
BS - baz.fxp
...
PD - qux.fxp
PD - quux.fxp
PD - corge.fxp
...
LD - grault.fxp
LD - garply.fxp
LD - waldo.fxp
...
PL - fred.fxp
PL - plugh.fxp
PL - xyzzy.fxp
...
DS - thud.fxp
...
...
...
I am trying to rename all batches with the same prefix with an incremental counter.
I had the idea first of storing all prefixes (with os.split
into a list or a collection) then using this list to scroll through the files in the directory.
I can't figure out how to reset the counter when the prefix changes.
A resulting example would be:
BS - 1.fxp
BS - 2.fxp
BS - 3.fxp
...
PD - 1.fxp
PD - 2.fxp
PD - 3.fxp
PD - 4.fxp
...
...
Here's the original code but incrementing through all files and not per batch of prefix.
import os, glob
path ='foo/bar/fox'
def prefix(f):
if f.endswith('.fxp'):
return(f.split(' -')[0])
os.chdir(path)
count = 0
for f in sorted(os.listdir(path), key = prefix):
if prefix(f) == f.split(' -')[0]:
count =+ 1
new_name = prefix(f) + '_' + str(count)+ '.fxp'
os.rename(f, new_name)
Any help is appreciated.