码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-02-16 18:52:22      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

 1 root@python-10:/home/liujianzuo/python/test# ls
 2 passwd  rc.local  test1
 3 root@python-10:/home/liujianzuo/python/test# py test1 -r EXIT exit /home/liujianzuo/python/test/rc.local 
 4       共修改了0行。
 5 root@python-10:/home/liujianzuo/python/test# py test1 -r exit EXIT /home/liujianzuo/python/test/rc.local 
 6 
 7 the new line is :
 8   第 6 行 : # Make sure that the script will "EXIT 0" on success or any other
 9 the word was replaced is : exit==>EXIT
10         
11 
12 the new line is :
13   第 16 行 : EXIT 0
14 the word was replaced is : exit==>EXIT
15         
16       共修改了2行。
17 root@python-10:/home/liujianzuo/python/test# cat test1 
18 #coding:utf-8
19 #!/usr/bin/env python
20 
21 import sys,os,subprocess
22 #a="liujianzuo"
23 if len(sys.argv) < 5:
24     exit("argc less than 4;like python test.py -r 准备替换的字符 要替换的字符 file_path_name")
25 
26 if -r in sys.argv:
27     ar1=sys.argv.index(-r)
28     ar2=sys.argv[ar1+ 1]
29     ar3=sys.argv[ar1 + 2]
30     filname= sys.argv[ar1 + 3]
31 else:
32     exit("the first argv must be -r ")
33 basedir = "%s/%s"%(os.path.dirname(filname),os.path.basename(filname))
34 f=file(%s%basedir,"r+")
35 sum1=0
36 numli=0
37 while True:
38     line=f.readline()
39     numli+=1
40     #print line
41     if ar2 in line:
42        # print "now pos+++>",f.tell()
43         f.seek(f.tell()-len(line))
44         #print f.tell()
45         new_line=line.replace(ar2,ar3)
46         f.write(new_line)
47         print """
48 \033[31;1mthe new line is :\033[0m
49   第 %s 行 : %s
50 the word was replaced is : \033[32;1m%s==>%s\033[0m
51         """ % (numli,new_line.strip(),ar2,ar3)
52         sum1+=1
53         continue
54         if line == "":
55             print "file is done  bye"
56             break
58     elif line == "":
59         break
60 print "\033[33;1m      共修改了%s行。\033[0m"%sum1
61 f.close()

 

技术分享

 

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

标签:

原文地址:http://www.cnblogs.com/liujianzuo888/p/5193267.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!