Python之路,Day22- Python基础-文件操作练习

先了解下with语法:

with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

1

2

3

with open('log','r') as f:

     

    ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, \

     open('log2') as obj2:

         pass

 

程序练习  

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

import sys
before_value = sys.argv[1]   输入的参数
after_value = sys.argv[2]


with open('file1','r',encoding='utf-8') as f1 ,\
      open('file2','w',encoding='utf-8') as f2:
    for line in f1 :
        if before_value in line:
            line = line.replace(before_value,after_value)
        f2.write(line)

猜你喜欢

转载自blog.csdn.net/sj349781478/article/details/81701457