博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
with管理文件操作
阅读量:7084 次
发布时间:2019-06-28

本文共 756 字,大约阅读时间需要 2 分钟。

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

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,如需转载请自行联系原作者

你可能感兴趣的文章
Full Gc经历分析
查看>>
Unity3D 判断鼠标是否按在UGUI上
查看>>
RichEdit
查看>>
在centos7上安装Jenkins
查看>>
Android——坐标系及转化
查看>>
android-problem——remount of /system failed: Read-only file system
查看>>
linux可执行文件添加到PATH环境变量的方法
查看>>
Loadrunner得到server參数
查看>>
LEMP平台全编译搭建
查看>>
Select * 一定不走索引是否正确?
查看>>
php-fpm 启动参数及重要配置详解
查看>>
GIS+=地理信息+容器技术(1)——容器技术概述
查看>>
libmemcached的安装及測试
查看>>
Elasticsearch之CURL命令的GET
查看>>
c++ 11 thread 初试
查看>>
项目PMO工作
查看>>
eclipse 执行MapReduce程序错误异常汇总(解决Map not fount)
查看>>
OpenCV实践之路——Python的安装和使用
查看>>
iOS上的http请求:get、post以及同步、异步
查看>>
【hdu 6172】Array Challenge(数列、找规律)
查看>>