f =open('files/readme.txt','r')
data = f.read()print(data)'''
1. 没有关闭文件
2. 即使关闭了文件,但在关闭之前如果抛出异常,仍然会无法关闭文件
'''
hello world
I love you
How are you?
f =open('files/readme.txt','r')try:
data = f.read()except:print('抛出异常')finally:
f.close()
withopen('files/readme.txt','r')as f:
data = f.read()print(data)
hello world
I love you
How are you?
2. 如何将with语句用于一个自定义类
'''
__enter__
__exit__
'''classMyClass:def__enter__(self):print('__enter__() is call!')return self
defprocess1(self):print('process1')defprocess2(self):
x =1/0print('process2')def__exit__(self, exc_type, exc_value, traceback):print('__exit__() is call!')print(f'type:{exc_type}')print(f'value:{exc_value}')print(f'trace:{traceback}')with MyClass()as my:
my.process1()
my.process2()
__enter__() is call!
process1
__exit__() is call!
type:<class 'ZeroDivisionError'>
value:division by zero
trace:<traceback object at 0x0000029AA9F98DC8>
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-10-b97c97f6e5f0> in <module>
23 with MyClass() as my:
24 my.process1()
---> 25 my.process2()
<ipython-input-10-b97c97f6e5f0> in process2(self)
13
14 def process2(self):
---> 15 x = 1/0
16 print('process2')
17 def __exit__(self, exc_type, exc_value, traceback):
ZeroDivisionError: division by zero