#!/usr/bin/python
#------------------------------------------------
#File : ctrl_hv2.0.py
#Date : 2014/08/28
#By : LinJK
#Version : Python 3.4.1
#Coding : UTF-8
#Note:
# When user input "example.txt oldword newword",
#a new output file "example_out.txt" is generated.
# The file can be input as "***.txt" or
#E:\..\***.txt
#------------------------------------------------
import os
import string
import cmd
import sys
print ("---", sys.argv, "---")
class REPL(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
print ("<<<<<<<Please input ? or help to show help>>>>>>")
print ("------------------------------------------------")
self.intro = '''u #Show usage
h #input info to do replacement
l #Show files in current directry.
q #exit current program
? #show commands that you can enter
'''
def help_u(self):
print ( "<HELP>Usage:<***.c/txt *** ***>" )
def do_u(self, line):
print ( "<HELP>Usage:<myfile.c old_word new_word>" )
print ( "<HELP>Input command<h> to begin replacement." )
#----------------------------------------------------------
def help_q(self):
print ("<HELP>Quits the program.")
def do_q(self, line):
print ("Bye !")
sys.exit()
#----------------------------------------------------------
def help_l(self):
print ("<HELP>List cur python file's path's or appointed path's info.")
def do_l(self, line):
print ("Please input path: ")
iDir=input(); #eg: input -- c:
listCurDir = os.listdir(iDir)
for lstdir in listCurDir:
print (lstdir)
#----------------------------------------------------------
def help_h(self):
print ("<HELP>Input info to do replacement")
def do_h(self, line):
print ("Please input filename, search_woed, new_word: ")
str_full_path=input()
lst_full_path=str_full_path.split(' ')
file=lst_full_path[0]
old=lst_full_path[1]
new=lst_full_path[2]
print ("***********************")
print("--->filename:", file)
print("--->oldword :", old)
print("--->newword :", new)
print ("***********************")
out=os.path.splitext(file)[0]+"_out.txt"
try:
os.remove(out)
except os.error:
pass
try:
fi=open(file)
except FileNotFoundError as err:
print(err)
print("------Begin Again------")
return
fo=open(out,"w")
for read_s in fi.readlines():
toWrite = str.replace(read_s,old,new)
fo.write(toWrite)
fi.close()
fo.close()
if __name__ == '__main__':
cdc = REPL()
cdc.cmdloop()
print( "End" )
Python__查找替换指定文件中的特定字符串
最新推荐文章于 2024-08-22 17:42:13 发布