python学习DAY7(文件修改)

#with方式打开文件(自动关闭关闭文件)
 (1)with open("YESTERDAY") as f:
          ...(文件的各种操作)
 (2)多个文件时
   with open("xxx".'r') as f ,\
        open("yesterday2",'r') as f2:
          ...(文件的各种操作)
 此时不需要手动关闭文件,则是自动关闭文件
#不覆盖原文件,对原文件进行修改后保存到新的文件里
f=open("YESTERDAY","r")
f_new=open("new.bak","w")

for line in f:
    if "像儿时的回忆" in line:
        line=line.replace("像儿时的回忆","")  
    f_new.write(line)
f.close()
f_new.close()

----------传参数替换字符串
import sys
f=open("YESTERDAY","r")
f_new=open("new.bak","w")
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()

 

posted @ 2019-06-29 21:52  LBC不认输  阅读(154)  评论(0编辑  收藏  举报