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 正则替换手机号 python手机号码替换_Python

批量替换存储过程内容脚本sp&lowbar;SqlReplace

开始 在数据库开发过程中,如果某一个表字段名被重命名.那么在使用到该字段的存储过程,对应的表字段名也要修改. 当存在多个存储都有使用该表字段,需要逐个去修改替换,是一件比较繁琐的事情,我们需要一个能实 ...

python全局替换文件内容脚本第1版

#!/usr/bin/python #coding=utf8 """ # Author: xiaoyafei # Created Time : 2018-05-08 09 ...

Python sh模块--------替换subprocess的利器

官方文档有句话"allows you to call any program",并且: helps you write shell scripts in Python by giv ...

孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容

孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 一.打开文件后,要务必记得关闭,所以一般的写法应当 ...

python 操作excel实现替换特定内容

本文介绍使用python语言,借助openyxl库来实现操作excel(xlsx)文件,实现替换特定内容的需求. 目前实现了3个小功能: 1. 全字匹配替换(mode1):(如:全字匹配 yocich ...

Python基于正则表达式实现文件内容替换的方法

Python基于正则表达式实现文件内容替换的方法 本文实例讲述了Python基于正则表达式实现文件内容替换的方法.分享给大家供大家参考,具体如下: 最近因为有一个项目需要从普通的服务器移植到SAE,而 ...

python file对象测试数据的读写操作及OS模块介绍(四)

import   from....import 引入模块 引入类 ①import 如果文件在lib下而且是python模块 :import 模块名. ②from....import from 包名.包 ...

python,获取用户输入,并且将输入的内容写到&period;txt

该功能缺点是必须保证该文件不存在的情况才会成功 f=open('E:/mywork/保存文件.txt','x') def userwrite(code): if code=='w': f.close( ...