Specify a folder, specify a file type, and replace the contents of all files under that folder.
Note that the read and write content under window needs to be coded, and #coding:utf-8 encoding should be specified in the file header to avoid coding problems.
Copy Code code as follows:
#coding: Utf-8
Import OS
Import Os.path
Path= '. '
Oldstr= '. php '
newstr= '. html '
For (Dirpath, Dirnames, filenames) in Os.walk (path):
For file in filenames:
If Os.path.splitext (file) [1]== '. html ':
Print (file)
Filepath=os.path.join (Dirpath,file)
Try
text_file = open (filepath, "R")
lines = Text_file.readlines ()
Text_file.close ()
Output = open (filepath, ' W ', encoding= ' utf-8 ')
For line in lines:
#print (line)
If not line:
Break
if (Oldstr in line):
TMP = Line.split (OLDSTR)
temp = Tmp[0] + newstr + tmp[1]
Output.write (temp)
Else
Output.write (line)
Output.close ()
Except Exception:
Print (Exception)
Break
This example allows you to bulk replace file names and content
Copy Code code as follows:
#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import OS, re
def multi_replace (text, adict):
Rx = re.compile (' | '). Join (Map (Re.escape, adict))
def xlat (Match):
Return Adict[match.group (0)]
Return Rx.sub (Xlat, text)
def batrename (CurDir, pairs):
FOR FN in Os.listdir (CurDir):
NEWFN = Multi_replace (FN, pairs)
If NEWFN!= fn:
Print ("Renames%s to%s in%s"% (FN, NEWFN, CurDir))
Os.rename (Os.path.join (CurDir, FN), Os.path.join (CurDir, NEWFN))
File = Os.path.join (CurDir, NEWFN)
If Os.path.isdir (file):
Batrename (file, pairs)
Continue
Text = open (file). Read ()
NewText = multi_replace (text, pairs)
If NewText!= text:
Print ("renames%s."% (file,))
Open (file, ' W '). Write (NewText)
If __name__== "__main__":
While True:
Oldname = Raw_input ("Old name:")
newname = Raw_input ("New Name:")
If Oldname and newname:
Batrename (Os.path.abspath ('. '), {oldname:newname})
Else:break