The examples in this article describe Python's way of traversing directories and replacing file names and directory names in batches. Share to everyone for your reference, as follows:
#encoding =utf-8#author:walker#date:2014-03-07#summary: Deep traverse the specified directory and change the subdirectory and file name to lowercase # Note that this program is for Windows only, Windows file (folder) name is not case-sensitive import osimport os.pathimport shutil# read into the specified directory and convert to absolute path RootDir = raw_input (' root dir:\n ') RootDir = Os.path.abspath (rootdir) print (' absolute root path:\n*** ' + rootdir + ' * * *) #先修改文件名for parent, dirnames, filenames in OS. Walk (RootDir): for filename in filenames:pathfile = os.path.join (parent, filename) pathfilelower = Os.path.join (PA Rent, Filename.lower ()) if Pathfile = = Pathfilelower: #如果文件名本身就是全小写 continue print (Pathfile +---+ PAT) Hfilelower) Os.rename (Pathfile, Pathfilelower) #后修改目录名, note the Topdown parameter here. #topdown决定遍历的顺序, if Topdown is true, the directory under top is enumerated first, then the directory, and so on, #反之, recursively enumerating the deepest subdirectories, then their sibling directories, and then the parent directory. #我们需要先修改深层的子目录for parent, Dirnames, filenames in Os.walk (RootDir, Topdown=false): for dirname in dirnames:pathdir = O S.path.join (parent, dirname) Pathdirlower = Os.path.join (parent, Dirname.lower ()) if Pathdir = = Pathdirlower: #如果文件夹 The name itself is all lowercase coNtinue Print (Pathdir +---+-Pathdirlower) os.rename (Pathdir, Pathdirlower)