Python way to traverse directories and bulk replace filenames and directory names

Source: Internet
Author: User
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) 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.