4.4文件操作:with

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4.4文件操作:with相关的知识,希望对你有一定的参考价值。

文件操作 with

With作用:不用写f.close,执行完with代码块,自动关闭相应文件
实例1:单个文件操作用with方法:

# -*-coding:utf-8 -*-
__author__ = ‘xiaojiaxin‘
__file_name__ = ‘with_method‘

f=open("log","r")
f.readline()
    f.read()
f.close()   #和下面的with等价

with open("log","r") as f:
    f.readline()
    f.read()
    #不再需要f.close().只要退出with代码块,自动close

实例2:多个文件操作用with方法

#创建操作多个文件,自动关闭
with open("log",‘r‘) as file1,open("paswd",‘r‘) as file2:
    file1.read()
    file2.read()

以上是关于4.4文件操作:with的主要内容,如果未能解决你的问题,请参考以下文章