How to recursively scroll file structure and rename directories in python

I would like to resursively rename directories by changing the last character to lowercase (if it's a letter)

I did this with my previous posts (sorry for duplicate posting and did not confirm answers)

This code works for files, but how can it be adapted for directories?

import fnmatch import os def listFiles(dir): rootdir = dir for root, subFolders, files in os.walk(rootdir): for file in files: yield os.path.join(root,file) return for f in listFiles(r"N:\Sonstiges\geoserver\IM_Topo\GIS\MAPTILEIMAGES_0\tiles_2"): if f[-5].isalpha(): os.rename(f,f[:-5]+f[-5].lower() + ".JPG") print "Renamed " + "---to---" + f[:-5]+f[-5].lower() + ".JPG" 
+6
source share
1 answer

The problem is that the default os.walk is an excess. If you try to rename directories while going down, the results are unpredictable.

Try installing os.walk up:

 for root, subFolders, files in os.walk(rootdir,topdown=False): 

Edit

Another problem you are facing is listFiles() returns, well, files are not directories.

This (unchecked) sub-subdirectory directories from the bottom up:

 def listDirs(dir): for root, subFolders, files in os.walk(dir, topdown=False): for folder in subFolders: yield os.path.join(root,folder) return 
+7
source

Source: https://habr.com/ru/post/902777/


All Articles