python file模块 替换输入内容脚本

 root@python-10:/home/liujianzuo/python/test# ls
passwd rc.local test1
root@python-10:/home/liujianzuo/python/test# py test1 -r EXIT exit /home/liujianzuo/python/test/rc.local
共修改了0行。
root@python-10:/home/liujianzuo/python/test# py test1 -r exit EXIT /home/liujianzuo/python/test/rc.local the new line is :
第 6 行 : # Make sure that the script will "EXIT 0" on success or any other
the word was replaced is : exit==>EXIT the new line is :
第 16 行 : EXIT 0
the word was replaced is : exit==>EXIT 共修改了2行。
root@python-10:/home/liujianzuo/python/test# cat test1
#coding:utf-8
#!/usr/bin/env python import sys,os,subprocess
#a="liujianzuo"
if len(sys.argv) < 5:
exit("argc less than 4;like python test.py -r 准备替换的字符 要替换的字符 file_path_name") if '-r' in sys.argv:
ar1=sys.argv.index('-r')
ar2=sys.argv[ar1+ 1]
ar3=sys.argv[ar1 + 2]
filname= sys.argv[ar1 + 3]
else:
exit("the first argv must be -r ")
basedir = "%s/%s"%(os.path.dirname(filname),os.path.basename(filname))
f=file('%s'%basedir,"r+")
sum1=0
numli=0
while True:
line=f.readline()
numli+=1
#print line
if ar2 in line:
# print "now pos+++>",f.tell()
f.seek(f.tell()-len(line))
#print f.tell()
new_line=line.replace(ar2,ar3)
f.write(new_line)
print """
\033[31;1mthe new line is :\033[0m
第 %s 行 : %s
the word was replaced is : \033[32;1m%s==>%s\033[0m
""" % (numli,new_line.strip(),ar2,ar3)
sum1+=1
continue
if line == "":
print "file is done bye"
break
elif line == "":
break
print "\033[33;1m 共修改了%s行。\033[0m"%sum1
f.close()

python file模块 替换输入内容脚本

上一篇:关于网站IIS日志分析搜索引擎爬虫说明


下一篇:LeetCode 43. 字符串相乘(Multiply Strings)