Search code examples
pythonlistrenameglobpython-os

Batch Rename files with different Prefixes but same file type using python


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.


Solution

  • I wrote this code for the same purpose back but you can modify it and re-use...

    import os
    # Function to rename multiple files
    def main():
       i = 0
       path="path to files"
       for filename in os.listdir(path):
          t = os.path.splitext(os.path.basename(f)) 
          my_dest = t[0] + str(i) + t[0]
          my_source =path + filename
          my_dest =path + my_dest
          # rename() function will
          # rename all the files
          os.rename(my_source, my_dest)
          i += 1
    # Driver Code
    if __name__ == '__main__':
       # Calling main() function
       main()