The examples in this article describe the classes that Python implements to search for files and replace them with content. Share to everyone for your reference. The implementation method is as follows:
#!/usr/bin/python-o# coding:utf-8 "" "-replace string in Files (recursive)-display the difference.v0.2-search_string can Be a Re.compile () object--use re.sub for replacingv0.1-initial version useable by a small "client" script, e.g.:- ------------------------------------------------------------------------------#!/usr/bin/python-o# Coding: Utf-8import sys, Re#sys.path.insert (0, "/path/to/git/repro/") # Please change Pathfrom replace_in_files import Searchandreplacesearchandreplace (Search_path = "/to/the/files/", # e.g.: simple string replace:search_string = ' The O LD string ', replace_string = ' The new string ', # e.g.: Regular expression replacing (used re.sub) #search_string = re.c Ompile (' {% URL (. *?)%} '), #replace_string = "{% url ' \g<1> '%}", search_only = True, # Display only the Differenc E #search_only = False, # write the new content file_filter= ("*.py",), # Fnmatch-filter)-------------------------------- -----------------------------------------------: Copyleft:2009-2011 by Jens Diemer "" "" __author__ = "Jens diemer" __license__ = "" "GNU general Public License V3 or ABOVE-HTT P://www.opensource.org/licenses/gpl-license.php "" "__url__ =" http://www.jensdiemer.de "__version__ =" 0.2 "Import OS, Re, Time, Fnmatch, difflib# fixme:see http://stackoverflow.com/questions/4730121/ Cant-get-an-objects-class-name-in-pythonre_type = TYPE (Re.compile ("")) class Searchandreplace (object): Def __init__ ( Self, Search_path, search_string, replace_string, Search_only=true, file_filter= ("* *",)): Self.sear Ch_path = Search_path self.search_string = search_string self.replace_string = replace_string self.search_only = Search_only self.file_filter = File_filter assert Isinstance (Self.file_filter, (list, tuple)) # Fixme:see http:/ /stackoverflow.com/questions/4730121/cant-get-an-objects-class-name-in-python self.is_re = isinstance (self.search _string, Re_type) print "Search '%s ' in [%s] ..."% (self.search_string, SElf.search_path) Print "_" * Time_begin = time.time () File_count = Self.walk () print "_" * Print '%s files searched in%0.2fsec. '% (File_count, (Time.time ()-Time_begin)) def Walk (self): File_count = 0 For Root, Dirlist, filelist in Os.walk (self.search_path): if ". SVN" in root:continue for filename in F Ilelist:for File_filter in Self.file_filter:if fnmatch.fnmatch (filename, file_filter): Self.s Earch_file (Os.path.join (root, filename)) File_count + = 1 return file_count def search_file (self, filepath): F = File (filepath, "r") Old_content = F.read () f.close () if Self.is_re or self.search_string in old_content: New_content = Self.replace_content (old_content, filepath) if self.is_re and new_content = Old_content:r Eturn Print filepath Self.display_plaintext_diff (old_content, new_content) def replace_content (self, Old_conten T, filepath): if self. is_re:new_content = Self.search_string.sub (self.replace_string, old_content) if new_content = = Old_content: return old_content else:new_content = Old_content.replace (self.search_string, self.replace_string If self.search_only! = False:return new_content print "Write new content into%s ..."% filepath, try: F = File (filepath, "w") F.write (new_content) f.close () except IOError, Msg:print "Error:", msg Else:print "OK" Print return new_content def display_plaintext_diff (self, Content1, Content2): "" "Disp Lay a diff. "" "Content1 = Content1.splitlines () Content2 = Content2.splitlines () diff = difflib. differ (). Compare (Content1, Content2) def is_diff_line (line): For Char in ("-", "+", "?"): If Line.startswit H (Char): return True return False print "line | text\n-------------------------------------------"old_line =" "In_block = False old_lineno = Lineno = 0 for line in Diff:if Line.startswith ("") or Line.startswith ("+"): Lineno + = 1 if Old_lineno = = Lineno:display_line = "%4s | %s "% (" ", Line.rstrip ()) Else:display_line ="%4s | %s "% (Lineno, Line.rstrip ()) if Is_diff_line (line): If not In_block:print" ... "# Display Previous line print Old_line In_block = True print display_line else:if in_block: # Display The next line aber a diff-block print display_line In_block = False Old_line = displ Ay_line Old_lineno = Lineno print "..." if __name__ = = "__main__": Searchandreplace (search_path= ".", # e.g. : Simple string replace:search_string= ' the old string ', replace_string= ' The new string ', # e.g.: Regular Express Ion replacing (used re.sub) #search_string = Re.compile (' {% URL (. *?)%} '), #replace_string = "{% url ' \g<1> ' %} ", Search_only=true, # Display only the difference# search_only = False, # write the new content file_filter= ("*.py",), # Fnmatch-filter )
Hopefully this article will help you with Python programming.