Skip to content

Commit 4004020

Browse files
committed
上下文管理器
1 parent d7b2dea commit 4004020

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

exercise/copy2_a.txt

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
中国
2+
美丽
3+
java
4+
go
5+
python
6+
北京
7+
上海
Loading

exercise/with_test.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# with语句可以自动管理上下文资源,
2+
# 不论什么原因跳出with块,都能保证文件正确的关闭,以此来达到释放资源的目的
3+
4+
"""
5+
MyContentMgr实现了特殊方法__enter__、__exit__,
6+
则称该类对象遵守了上下文管理器
7+
"""
8+
9+
10+
class MyContentMgr(object):
11+
def __enter__(self):
12+
print('enter方法被调用执行了')
13+
return self
14+
15+
def __exit__(self, exc_type, exc_val, exc_tb):
16+
print('exit方法被调用执行了')
17+
18+
def show(self):
19+
# print('show方法被调用执行了', 1 / 0)
20+
print('show方法被调用执行了')
21+
22+
23+
print(type(open('a.txt', 'r', encoding='UTF-8')))
24+
print(dir(open('a.txt', 'r', encoding='UTF-8')))
25+
# 原理是:_io.TextIOWrapper类实现了__enter__和__exit__方法,
26+
# 离开运行时上下文,会自动调用上下文管理器的特殊方法__exit__(即使抛出了异常仍会执行)
27+
with open('a.txt', 'r', encoding='UTF-8') as file:
28+
print(file.read())
29+
30+
with MyContentMgr() as file:
31+
file.show()
32+
33+
# 复制文件
34+
with open('a.txt', 'rb') as src_file:
35+
with open('copy2_a.txt', 'wb') as target_file:
36+
target_file.write(src_file.read())

0 commit comments

Comments
 (0)