Python3学习之路~2.8 文件操作实现简单的shell sed替换功能

程序:实现简单的shell sed替换功能

#实现简单的shell sed替换功能,保存为file_sed.py
#打开命令行输入python file_sed.py 我 Alex,回车后会把文件中的“我”全部替换为“Alex”
import sys
find_str=sys.argv[1]
replace_str=sys.argv[2]

f=open("yesterday.txt",'r',encoding='UTF-8')
f_new=open("yesterday.bak",'w',encoding='UTF-8')

for line in f:
    if find_str in line:
        line=line.replace(find_str,replace_str)
    f_new.write(line)

f.close()
f_new.close()
View Code

 

posted @ 2018-06-21 18:05  zhengna  阅读(198)  评论(0编辑  收藏  举报