Python method of traversing a directory and changing the file name and directory name in batches

  • 2020-05-12 02:48:22
  • OfStack

This example shows how Python can traverse a directory and change file and directory names in batches. I will share it with you for your reference as follows:


#encoding=utf-8
#author: walker
#date: 2014-03-07
#summary:  Deep traverses the specified directory and changes subdirectories and file names to lowercase 
# Note that this program is only for windows . windows The following file (folder) name is not case sensitive 
import os
import os.path
import shutil
# Reads into the specified directory and converts to the absolute path 
rootdir = raw_input('root dir:\n')
rootdir = os.path.abspath(rootdir)
print('absolute root path:\n*** ' + rootdir + ' ***')
# I'm gonna change the file name 
for parent, dirnames, filenames in os.walk(rootdir):
  for filename in filenames:
    pathfile = os.path.join(parent, filename)
    pathfileLower = os.path.join(parent, filename.lower())
    if pathfile == pathfileLower:  # If the file name itself is all lowercase 
      continue
    print(pathfile + ' --> ' + pathfileLower)
    os.rename(pathfile, pathfileLower)
# After the change directory name, note here topdown Parameters. 
#topdown Determine the order of traversal, if topdown for True , then list first top Under the directory, then the directory of the directory, and so on; 
# Instead, recursively enumerate the deepest subdirectory, then its sibling, then its parent. 
# We need to modify the deep subdirectory first 
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: # If the folder name itself is all lowercase 
      continue
    print(pathdir + ' --> ' + pathdirLower)
    os.rename(pathdir, pathdirLower)

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", commonly used traversal Python skills summary, Python pictures skills summary, "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article is helpful to you Python programming.


Related articles: