bionicsleuth
bionicsleuth

Reputation: 83

How to add an incremental suffix to a list of files

I am looking for a way to take a list of files that could be called anything, rename the file to match the name of the folder the file is within and increment a suffix.

e.g.

 Folder
  |
  |
  |---> File.ext
  |---> File.ext
  |---> File.ext

and the result of the script would be:

Folder
  |
  |
  |---> Folder01.ext
  |---> Folder02.ext
  |---> Folder03.ext  

I've got the code to rename the files the same as the parent-folder (see below) however i'm unsure where and how to include the code to increment the suffix.



def walkDir(rootDir):

    for thisDir, thisDir_subDirs, thisDir_files in os.walk(rootDir):

        for filename in thisDir_files:

            basename = ntpath.basename(filename)
            name, ext = os.path.splitext(basename)  
            newname = ntpath.split(thisDir)[1]
            newfilename = ''.join([newname, ext])
            src = os.path.join(thisDir, filename)
            dst = os.path.join(thisDir, newfilename)   
            os.rename(src, dst)

        for rootDir in thisDir_subDirs:
            walkDir(rootDir)

Upvotes: 1

Views: 299

Answers (1)

Chris
Chris

Reputation: 16147

enumerate is usually good for this. You can use the counter i generated by enumerate inside your ''.join() and use zfill to pad it with a zero

for i, filename in enumerate(thisDir_files):

            basename = ntpath.basename(filename)
            name, ext = os.path.splitext(basename)  
            newname = ntpath.split(thisDir)[1]
            newfilename = ''.join([newname, str(i).zfill(2),ext])
            src = os.path.join(thisDir, filename)
            dst = os.path.join(thisDir, newfilename)   
            os.rename(src, dst)

Upvotes: 1

Related Questions