This article describes how Python traverses directories and replaces file names and directory names in batches. Share to everyone for your reference, specific as follows:
#encoding =utf-8 #author: Walker #date: 2014-03-07 #summary: Depth traverse the specified directory and change the subdirectory and file name to lowercase #注意, this program is only for Windows, Windows file (folder) name is case-insensitive import OS import os.path import shutil #读入指定目录并转换为绝对路径 RootDir = raw_input (' root dir:\n ') RootDir = O S.path.abspath (rootdir) print (' absolute root path:\n*** ' + rootdir + ' * * *) #先修改文件名 for parent, dirnames, filenames in O S.walk (ROOTDIR): for filename in filenames:pathfile = os.path.join (parent, filename) Pathfilelower = Os.path.jo In (parent, filename.lower ()) if Pathfile = = Pathfilelower: #如果文件名本身就是全小写 continue print (Pathfile + '-->
' + pathfilelower ' os.rename (pathfile, Pathfilelower) #后修改目录名, here Note the Topdown parameter.
#topdown决定遍历的顺序, if Topdown is true, first enumerate the directories under top, then directories, and so on #反之, recursively enumerate 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 = Os.path.join (parent, dirname) Pathdirlower = Os.path.join (parent, Dirname.lower ()) if Pathdir = = PathdiRlower: #如果文件夹名本身就是全小写 Continue print (Pathdir + '--> ' + pathdirlower) os.rename (Pathdir, Pathdirlower)
More information about Python-related content can be viewed in this site: "Python file and directory operation tips Summary", "Python text file Operation tips Summary", "Python Common traversal Skills Summary", "Python Picture Operation tips Summary", " Python data structure and algorithm tutorial, Python socket Programming Tips Summary, Python function Usage tips Summary, python string manipulation tips and Python introductory and advanced classic tutorials
I hope this article will help you with Python programming.