对比两种打开文件的方式,得出的一个点:
先对比一下
'''传统的打开文件操作,
为了预防打开文件流出现错误,
所以需要用try语句异常处理,
同时也是为了无论能否正常打开文件,
最后都要关闭文件流'''
try:
file = open("1.txt","r")
file_data = file.read()
print(file_data)
except Exception as e:
print(e)
finally:
file.close()
'''with方式打开文件,
不需要异常处理语句,
也不需要手动调用close()关闭文件流,无论异常是否都会自动关闭文件流'''
with open("1.txt","r") as f:
file_data = f.read()
print(file_data)
得出with语句和上下文管理器结合使用:
第一种:
'''上下文管理器:在类里面实现__enter__和__exit__方法,
创建的对象就是上下文对象'''
class File(object):
def __init__(self,file_name,file_mode):
self.file_name = file_name
self.file_mode = file_mode
def __enter__(self):
#上文方法,负责返回操作对象
self.file = open(self.file_name,self.file_mode)
return self.file
#当with语句执行完成,自动执行,不管是否出现异常
def __exit__(self, exc_type, exc_val, exc_tb):
#下文方法,负责释放对象
print("over")
self.file.close()
with File('1.txt','r') as f:
file_data = f.read()
print(file_data)
第二种:函数式上下文
from contextlib import contextmanager
@contextmanager
def my_open(file_name,file_mode):
try:
file = open(file_name,file_mode)
#yield关键字之前的代码可视为上文,负责返回操作对象
yield file
except Exception as e:
print(e)
finally:
#yield关键字之后的代码可视为下文,负责释放操作对象
file.close()
with my_open('1.txt','r') as f:
file_data = f.read()
print(file_data)