且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

with管理文件操作

更新时间:2022-09-26 09:26:00

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

1
2
3
with open('log','r') as f:        f.write('xxxxxx')
    f.readlines()
    ...................


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

以往我们打开文件一般用如下方法:

1
2
3
obj = open('log','r')
obj.write('abcdefg')
obj.close()


如果运用with,则可以将上述代码改写为:

1
2
3
with open('log','r') as f:
     f.write('abcdefg')
     f.readlines()


另外在Python2.7之后支持能同时打开多个文件,即:

1
with open('file1','r') as  obj1,open('file2','w')  as  obj2




示例代码:(修改配置文件)

1
2
3
4
with open('log1','r') as obj1, open('log2','w') as obj2:
        for line in obj1:
              new_line = line.replace('10.0.0.10','10.0.0.100')
              obj2.write(new_line)


后面再继续check 测试,如果测试通过,则可以将log1改名为log1.bak,log2改名为log1,这样就完成了

配置文件的修改






      本文转自027ryan  51CTO博客,原文链接:http://blog.51cto.com/ucode/1719396,如需转载请自行联系原作者