• 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()

  • 相关阅读:
    python--函数的返回值、函数的参数
    python--字典,解包
    Vue--ElementUI实现头部组件和左侧组件效果
    Vue--整体页面布局
    jmeter--non GUI
    python--切片,字符串操作
    celery--调用异步任务的三种方法和task参数
    celery--实现异步任务
    celery--介绍
    开发问题记录
  • 原文地址:https://www.cnblogs.com/liujianzuo888/p/5193267.html
Copyright © 2020-2023  润新知