Search code examples
pythongoogle-colaboratory

Recursively rename .json files sequentially in subdirectories


I am trying to rename a bunch of .JSON files that exist in subfolders in my Google Drive by traversing the root folder with glob function. Since there are thousands of subfolders,

There are two issues I am having with the code I am running to rename those files:

First issue is when running the code (even without the recursive function, that is specifying folders manually), the code seems to randomly rename files, whereas I need them in order, like the 'zero_000000000_keypoints' need to be renamed to 'image_00000_keypoints', basically name-wise. I want them to be renamed sequentially basically, so the order is right.

Second problem is whilst using the recursive method, the renamed files are being saved in the root folder in 'src' and not in the folder it's in.

import os
import glob
import re

src = r'/content/drive/MyDrive/Project/jsonfiles'
ext = '.json'
i = 0
for filename in glob.glob(os.path.join(src,'**/*' + ext), recursive=True):
    if not re.search('image_\d\d\d' + re.escape(ext) +'$',filename):
        while True:
            newname = os.path.join(src,'image_{:05d}_keypoints{}'.format(i,ext))
            if os.path.exists(newname):
                i += 1
            else:
                break
        print('renaming "%s" to "%s"...' % (filename, newname))
        os.rename(filename,newname)

Could someone please help fix the above issues?

Thank you


Solution

  • The first issue is due to the fact that glob does not return files in the order you expect. The most efficient way to fix this depends on the structure of the original filenames.

    The second issue is due to the fact that you do not take into account the path the file to be renamed is located in and always use src as the base path.

    A possible fix would be:

    dirname = os.path.dirname(filename)
    newname = os.path.join(dirname, 'image_{:05d}_keypoints{}'.format(i,ext))