Python小程序之sed命令替换
2024-09-28 06:30:53
需求:
编写sed命令脚本
代码如下
# Author:Lee Sir import sys,os des_file = r'E:\StartPython\day3\test.txt'
des_file1 = r'E:\StartPython\day3\test1.txt' parameter = ['','Somehow','',des_file] def usage(parameter):
if len(parameter) == 4:
if isinstance(parameter[1],str) and isinstance(parameter[2],str):
old_str = parameter[1]
new_str = parameter[2]
if os.path.exists(parameter[3]):
des_file = parameter[3]
return True, old_str, new_str, des_file
return False def check_string_exist(old,file):
with open(file,encoding='utf-8') as fd:
for line in fd:
if old not in line:
return False
else:
return True def replace(old,new,file):
with open(file,'r+',encoding='utf-8') as fd,open(des_file1,'w+',encoding='utf-8') as fd1:
for line in fd:
if old in line:
new_line = line.replace(old,new)
else:
new_line = line
print(new_line)
fd1.write(new_line) def main():
result = usage(parameter)
if result:
if check_string_exist(result[1],result[3]):
replace(result[1],result[2],result[3])
else:
print('the %s is not found in %s ' % (result[1],result[3]))
else:
exit('USAGE: %s old_str new_str des_file' % sys.argv[0]) if __name__ == '__main__':
main()
最新文章
- AX 2012 template table use in Query
- vim 查找时忽略大小写
- hdu 5444 Elven Postman
- 【转】rvm安装ruby,gem,rails,之后仍然无法找到rails命令
- ssh(Struts2+hibernate+spring)简单分页
- C# TypeConverter 数据转换
- 点击itemView选中checkbox
- jQuery 焦点图,图像文件js档
- unity 创建NGUI字体
- Unity3D NGUI事件监听的综合管理
- SQLALCHEMY_TRACK_MODIFICATIONS adds significant异常的解决方法
- c# 后台绑定treeview 多个tab
- CentOS7 YUM安装与配置 MySQL5.7
- linux中一些简便的命令之tr
- 修改Devexpress DateEdit控件默认的日期格式和日历风格
- 数据库sql优化总结之1-百万级数据库优化方案+案例分析
- 通过父类定位到子类 先将父类当作一个dom
- POJ3581:Sequence——题解
- 2014蓝桥杯B组初赛试题《李白打酒》
- C++11写算法之插入排序