This article describes how Python implements a bulk replacement of file extensions in a specified directory. Share to everyone for your reference, specific as follows:
#encoding =utf-8 #author: Walker #date: 2013-12-06 #function: Depth Traversal specified directory, replace the specified extension import OS import os.path #读入指定目录并转换为绝对路径 ro Otdir = raw_input (' root dir:\n ') RootDir = Os.path.abspath (rootdir) print (' absolute path:\n ' + rootdir) #读入原扩展名并标准化 old_ex t = raw_input (' Old extension:\n ') Old_ext = Old_ext.strip () if old_ext[0]!= '. ': Old_ext = '. ' + old_ext #读入新扩展名并标准化 NE W_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.rena Me (Pathfile, New_pathfilE
PS: The above features a shell command can also be implemented
#将后缀. ini to. txt
#路径名可以是相对路径或绝对路径 find
path name | rename ' s/\.ini$/\.txt/'
Note that the rename command above is the Perl version of the Rename command.
PS2:scandir compatible code.
# Use the built-in version of Scandir/walk if possible, otherwise
# with the Scandir module version
try:
from OS import scandir, walk #python3.5+
except Importerror:
from scandir import scandir, walk #python3.4-
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 URL operation tips 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.