# Auther: Aaron Fan
'''
思路:
目的是为了修改yesterday这个文件,但是因为无法直接去修改这个文件,所以需要先把修改好的内容写入高yesterday.new这个文件中,
然后再把yesterday.new的内容覆盖到yesterday这个文件中
f = open('yesterday','r',encoding='utf-8')
f_new = open('yesterday.new','w',encoding='utf-8')
for line in f:
if "肆意的快乐等我享受" in line:
line = line.replace("肆意的快乐等我享受","肆意的快乐等着Aaron去享受")
f_new.write(line)
f.close()
f_new.close()
#改进版(实现类似sed的功能):
import sys
f = open('yesterday','r',encoding='utf-8')
f_new = open('yesterday.new','w',encoding='utf-8')
#命令行参数,需要被改的字符串
find_str = sys.argv[1]
#命令行参数,需要被改成哪个字符串
replace_str = sys.argv[2]
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()
#需要在命令行下去测试(源文件yesterday需要存在的),使用以下命令:
#python file文件的修改_实现类似sed的功能.py "肆意的快乐等我享受" "肆意的快乐等着Aaron去享受"
'''
#使用with语句的改进版(with的作用就是,当with语句执行完后会自动帮你关闭文件,所以文件操作请用with):
import sys
with open('yesterday','r',encoding='utf-8') as f,
open('yesterday.new','w',encoding='utf-8') as f_new:
#命令行参数,需要被改的字符串
find_str = sys.argv[1]
#命令行参数,需要被改成哪个字符串
replace_str = sys.argv[2]
for line in f:
if find_str in line:
line = line.replace(find_str,replace_str)
f_new.write(line)
#需要在命令行下去测试(源文件yesterday需要存在的),使用以下命令:
#python file文件的修改_实现类似sed的功能.py "肆意的快乐等我享受" "肆意的快乐等着Aaron去享受"