Question

We just switched over our storage server to a new file system. The old file system allowed users to name folders with a period or space at the end. The new system considers this an illegal character. How can I write a python script to recursively loop through all directories and rename and folder that has a period or space at the end?

Was it helpful?

Solution

Use os.walk. Give it a root directory path and it will recursively iterate over it. Do something like

for root, dirs, files in os.walk('root path'):
    for dir in dirs:
        if dir.endswith(' ') or dir.endswith('.'):
            os.rename(...)

EDIT:

We should actually rename the leaf directories first - here is the workaround:

alldirs = []
for root, dirs, files in os.walk('root path'):
    for dir in dirs:
        alldirs.append(os.path.join(root, dir))

# the following two lines make sure that leaf directories are renamed first
alldirs.sort()
alldirs.reverse()

for dir in alldirs:
    if ...:
        os.rename(...)

OTHER TIPS

You can use os.listdir to list the folders and files on some path. This returns a list that you can iterate through. For each list entry, use os.path.join to combine the file/folder name with the parent path and then use os.path.isdir to check if it is a folder. If it is a folder then check the last character's validity and, if it is invalid, change the folder name using os.rename. Once the folder name has been corrected, you can repeat the whole process with that folder's full path as the base path. I would put the whole process into a recursive function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top