Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename all folders?

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?

like image 699
LA_ Avatar asked Aug 05 '12 12:08

LA_


1 Answers

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.

like image 150
Martijn Pieters Avatar answered Oct 13 '22 12:10

Martijn Pieters