1
2
3
4
5
6
7
8
9
10
11
12
|
import
contextlib
@contextlib
.contextmanager
def
myopen(
file
, mode):
f
=
open
(
file
, mode, encoding
=
"utf-8"
)
try
:
yield
f
finally
:
f.close()
with myopen(
"01-thread.py"
,
'r'
) as f:
print
(f.read())
|
这里使用Python contextlib模块模拟了我们常用的with open功能,这里使用了contextlib.contextmanager装饰器,不能缺失!
本文转自戴柏阳的博客博客51CTO博客,原文链接http://blog.51cto.com/daibaiyang119/1964018如需转载请自行联系原作者
daibaiyang119