Today released the newly completed Python script toolbox of the bulk replacement directory for all specified extensions in the file with the specified string, command-line parameter processing instead of using the Argparse library, the Python code is as follows:
#!/usr/bin/python2.7#-*-encoding:utf-8-*-# Copyright [email protected] "" "Replace old string with new string The specified string from the all files in PATH bulk replaces the directory with all specified extensions Usage:python replace_str.py-o old-n new-p your_path-e file_extension "" "__author__ = ['" Xitao ":<[email protected]> ']import sysimport osimport reimport shutilfrom argparse Import Argumentparserdef Replace_path (p, old, new, suffix= ' txt '): # Pass path and two strings as parameters Workdir = P Os.chdir (workdir) CWD = OS.GETCWD () dirs = Os.listdir (CWD) for tmp in Dirs:path = Os.path.join (CWD, tmp) #print ' path= ', PA Th #如果是文件 if Os.path.isfile (path): #判断文件扩展名 if Os.path.splitext (TMP) [1][1:] = = suffix: with open (path) as F:data = F.read () #print data data_ne W = re.sub (old, new, data) if data_new! = Data:temp = Path + ". Bak" With open (temp, ' WB ') as FneW:fnew.write (data_new) shutil.move (temp, path) print ("Re Place file {0} to {1} ' in {2} '. Format (old, new, path) #如果是路径, recursive elif os.path.isdir (path): Print ("Enter dir:" + path) Replace_path (path, old, new, suffix) if __name__ = = "__main__": p = Argument Parser (usage= ' python replace_str.py-o old-n new-p your_path-e file_extension ', description= ' rep Lace old string with new string from all specific extension files in path ') p.add_argument ('-O ', '--old ', default= ', h elp= ' old string want to be replaced ') p.add_argument ('-n ', '--new ', default= ', help= ' new string ') p.add_argument ('- P ', '--path ', default= "./", help= ' target directory ') p.add_argument ('-e ', '--ext ', default= "txt", help= ' target file ext Ension ') # This function divides the recognized and the non-known parameters into 2 variables, args, remaining = P.parse_known_args (sys.argv) print (args) print (remaining ) If Args.old and argS.new:print (Args.old) Replace_path (Args.path, Args.old, Args.new, Args.ext)
The bulk replacement directory of the Python script Toolbox in Ko Tao the specified string in all files with the specified extension