Python implements file name bulk substitution and content substitution _python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.