Search code examples
pythonfilerenaming

Python, Renaming Subdirectors


(using 2.7)

Currently having an issue, and i've been attempting to go through the processes of os.walk / os.rename. But at the current time, only the main file is getting appended with _final, instead of all the files inside of that one as well.

So for example

Main ---> sub1 -> sub2 -> sub3

Needs to be

Main_final (currently stopping here) ----> sub1_final -> sub2_final -> sub3_final

Here's my code at the moment,

import shutil
import sys
import os

def rename():
        ### pseudo
        for folderName, subfolders, filenames in os.walk(path, topdown=##???):
            for subfolder in subfolders:
                print subfolder
                os.rename(os.path.join(folderName, subfolders), os.path.join(folderName, subfolders + 'rename'))

            print('')

    else:
        print("Directory does not exist")

if __name__ == '__main__':
    copy()

Solution

  • Walk the tree with topdown set to False - Rename sub-directories first, and top-level directories last, renaming top-level directories will no longer affect the sub-directories.

    From Documentation

    If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.

    When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.

    import os
    
    path = "path/to/folder"
    for root, dirs, files in os.walk(path, topdown=False):
        for dirname in dirs:
            print os.path.join(root, dirname)
            os.rename(os.path.join(root, dirname), os.path.join(root, dirname+"_Final"))