How to rename all folders?
Asked Answered
S

1

5

I have the code like below:

temp = os.walk(sys.argv[1])
for root, dirs, files in temp:
    for i in dirs:
        dir = os.path.join(root,i)
        os.rename(dir, dir+"!")

It works almost ok. But once parent folder is renamed, it can not rename subfolders. How can I avoid that?

Saint answered 5/8, 2012 at 12:14 Comment(0)
E
9

Walk the tree with topdown set to False instead:

temp = os.walk(sys.argv[1], topdown=False)
for root, dirs, files in temp:
    for i in dirs:
        dir = os.path.join(root,i)
        os.rename(dir, dir+"!")

From the 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).

Thus, you get to rename sub-directories first, and will see the top-level directories last, and renaming them will no longer affect how the sub-directories are found.

Eyepiece answered 5/8, 2012 at 12:16 Comment(1)
@Saint I have an incident question: are path and directory the same thing in Python ? I tried your piece of code with a directory name instead of sys.argv[0] like that temp = os.walk('F:\\WORK\\ALGOCODE') and dirs list is empty. I am ok from doc with Martijn explanation.Ducky

© 2022 - 2024 — McMap. All rights reserved.