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?
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 isFalse
, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With