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

yipeiwu_com7年前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程序设计有所帮助。

相关文章

win10安装tesserocr配置 Python使用tesserocr识别字母数字验证码

win10安装tesserocr配置 Python使用tesserocr识别字母数字验证码

链接:https://pan.baidu.com/s/1l2yiba7ZTPUTf41ZnJ4PYw 提取码:t3bq win10安装tesserocr 首先需要下载tesseract,...

Python版微信红包分配算法

红包分配算法代码实现发给大家,祝红包大丰收! #coding=gbk import random import sys #print random.randint(0, 99)...

tensorflow estimator 使用hook实现finetune方式

为了实现finetune有如下两种解决方案: model_fn里面定义好模型之后直接赋值 def model_fn(features, labels, mode, params):...

Python中使用urllib2防止302跳转的代码例子

说明:python的urllib2获取网页(urlopen)会自动重定向(301,302)。但是,有时候我们需要获取302,301页面的状态信息。就必须获取到转向前的调试信息。 下面代码...

10 行Python 代码实现 AI 目标检测技术【推荐】

10 行Python 代码实现 AI 目标检测技术【推荐】

只需10行Python代码,我们就能实现计算机视觉中目标检测。 from imageai.Detection import ObjectDetection import os ex...