Python小程序之sed命令替换

需求:

  编写sed命令脚本

 

代码如下

 1 # Author:Lee Sir
 2 
 3 import sys,os
 4 
 5 des_file = r'E:\StartPython\day3\test.txt'
 6 des_file1 = r'E:\StartPython\day3\test1.txt'
 7 
 8 parameter = ['0','Somehow','123',des_file]
 9 
10 def usage(parameter):
11     if len(parameter) == 4:
12         if isinstance(parameter[1],str) and isinstance(parameter[2],str):
13             old_str = parameter[1]
14             new_str = parameter[2]
15             if os.path.exists(parameter[3]):
16                 des_file = parameter[3]
17                 return True, old_str, new_str, des_file
18     return False
19 
20 def check_string_exist(old,file):
21     with open(file,encoding='utf-8') as fd:
22         for line in fd:
23             if old not in line:
24                 return False
25             else:
26                 return True
27 
28 def replace(old,new,file):
29     with open(file,'r+',encoding='utf-8') as fd,open(des_file1,'w+',encoding='utf-8') as fd1:
30         for line in fd:
31             if old in line:
32                 new_line = line.replace(old,new)
33             else:
34                 new_line = line
35             print(new_line)
36             fd1.write(new_line)
37 
38 def main():
39     result = usage(parameter)
40     if result:
41         if check_string_exist(result[1],result[3]):
42             replace(result[1],result[2],result[3])
43         else:
44             print('the %s is not found in %s ' % (result[1],result[3]))
45     else:
46         exit('USAGE: %s  old_str  new_str  des_file' % sys.argv[0])
47 
48 if __name__ == '__main__':
49     main()

 

转载于:https://www.cnblogs.com/dachenzi/p/6595910.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值