Python with关键字,上下文管理器,@contextmanager文件操作示例

yipeiwu_com6年前Python基础

本文实例讲述了Python with关键字,上下文管理器,@contextmanager文件操作。分享给大家供大家参考,具体如下:

demo.py(with 打开文件):

# open 方法的返回值赋值给变量 f,当离开 with 代码块的时候,系统会自动调用 f.close() 方法
# with 的作用和使用 try/finally 语句是一样的。
with open("output.txt", "r") as f:
  f.write("XXXXX")

demo.py(with,上下文管理器):

# 自定义的MyFile类
# 实现了 __enter__() 和 __exit__() 方法的对象都可称之为上下文管理器
class MyFile():
  def __init__(self, filename, mode):
    self.filename = filename
    self.mode = mode
  def __enter__(self):
    print("entering")
    self.f = open(self.filename, self.mode)
    return self.f
  # with代码块执行完或者with中发生异常,就会自动执行__exit__方法。
  def __exit__(self, *args):
    print("will exit")
    self.f.close()
# 会自动调用MyFile对象的__enter__方法,并将返回值赋给f变量。
with MyFile('out.txt', 'w') as f:
  print("writing")
  f.write('hello, python')
  # 当with代码块执行结束,或出现异常时,会自动调用MyFile对象的__exit__方法。
 

demo.py(实现上下文管理器的另一种方式):

from contextlib import contextmanager
@contextmanager
def my_open(path, mode):
  f = open(path, mode)
  yield f
  f.close()
# 将my_open函数中yield后的变量值赋给f变量。
with my_open('out.txt', 'w') as f:
  f.write("XXXXX")
  # 当with代码块执行结束,或出现异常时,会自动执行yield后的代码。

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python文件与目录操作技巧汇总》、《Python文本文件操作技巧汇总》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python实现读取SQLServer数据并插入到MongoDB数据库的方法示例

本文实例讲述了Python实现读取SQLServer数据并插入到MongoDB数据库的方法。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- impo...

Windows下python2.7.8安装图文教程

Windows下python2.7.8安装图文教程

本文为大家分享了python2.7.8安装图文教程,供大家参考,具体内容如下 1、进入python的官方网站下载:https://www.python.org/,点击Download,选...

使用 tf.nn.dynamic_rnn 展开时间维度方式

使用 tf.nn.dynamic_rnn 展开时间维度方式

对于单个的 RNNCell , 使用色的 call 函数进行运算时 ,只是在序列时间上前进了一步 。如使用 x1、 ho 得到此h1, 通过 x2 、 h1 得到 h2 ...

python实现生成Word、docx文件的方法分析

本文实例讲述了python实现生成Word、docx文件的方法。分享给大家供大家参考,具体如下: http://python-docx.readthedocs.io/en/latest/...

numpy.random.shuffle打乱顺序函数的实现

numpy.random.shuffle 在做将caffe模型和预训练的参数转化为tensorflow的模型和预训练的参数,以便微调,遇到如下函数: def gen_data(so...