zoukankan      html  css  js  c++  java
  • python file模块 替换输入内容脚本

     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 33[31;1mthe new line is :33[0m
    49   第 %s 行 : %s
    50 the word was replaced is : 33[32;1m%s==>%s33[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 "33[33;1m      共修改了%s行。33[0m"%sum1
    61 f.close()

  • 相关阅读:
    福大软工1816 · 第二次作业
    团队第一次作业
    软工实践 第三次作业 结对作业一
    软件工程-个人项目
    白茫茫一片真干净·福大软工1816 · 第一次作业
    Alpha 冲刺 (3/10)
    Alpha冲刺 (2/10)
    Alpha 冲刺(1)
    福大软工 · 第七次作业——需求分析报告
    福大软工 · 第八次作业(课堂实战)- 项目UML设计(团队)
  • 原文地址:https://www.cnblogs.com/liujianzuo888/p/5193267.html
Copyright © 2011-2022 走看看