Python implements the method of batch replacement of file extensions under the specified directory

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

The example in this article describes how Python implements bulk replacement of file extensions in a specified directory. I will share it with you for your reference as follows:


#encoding=utf-8
#author: walker
#date: 2013-12-06
#function:  To deeply traverse the specified directory, change the specified extension 
import os
import os.path
# Reads into the specified directory and converts to the absolute path 
rootdir = raw_input('root dir:\n')
rootdir = os.path.abspath(rootdir)
print('absolute path:\n' + rootdir)
# Read in the original extension and standardize 
old_ext = raw_input('old extension:\n')
old_ext = old_ext.strip()
if old_ext[0] != '.':
  old_ext = '.' + old_ext
# Read in the new extension and standardize 
new_ext = raw_input('new extension:\n')
new_ext = new_ext.strip()
if new_ext[0] != '.':
  new_ext = '.' + new_ext
for parent, dirnames, filenames in os.walk(rootdir):
  for filename in filenames:
    pathfile = os.path.join(parent, filename)
    if pathfile.endswith(old_ext):
      new_pathfile = os.path.splitext(pathfile)[0] + new_ext
      print('=======================================================')
      print(pathfile)
      print('-------------------------------------------------------')
      print(new_pathfile)
      print('=======================================================')
      os.rename(pathfile, new_pathfile)

PS: one shell command is also available


# The suffix .ini Switch to .txt
# Path names can be relative or absolute 
find  The path name  | rename 's/\.ini$/\.txt/'

Note that the rename command above is the rename command of the perl version.

PS2: compatible code for scandir.


# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
  from os import scandir, walk  #python3.5+
except ImportError:
  from scandir import scandir, walk #python3.4-

More about Python related topics: interested readers to view this site "Python file and directory skills summary", "Python skills summary text file", "Python URL 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 for you to design Python program.


Related articles: