zoukankan      html  css  js  c++  java
  • Python环境下文本的输入与with..as的使用

     

    学习Python语言中,想读取桌面文件dict2.txt;写了两种形式:

    f= open('C:/Users/lgsjb/Desktop/dict2.txt') #注意斜杠问题:是/而不是
    all_the_text=f.readlines() #这里必须用这种形式,不能直接输入f.readlines()否则只会弹出[]
    #lines=f.readlines 这里应该是变量类型的问题,会造成for line in lines 弹出错误
    print(all_the_text)
    f.close()
    file_object =open('C:/Users/lgsjb/Desktop/dict2.txt')
    try :
    all_the_text=file_object.read()
    print(all_the_text)
    finally :
    file_object.close() 

    对照这两种形式,第一种读取结果是文本内容被整合在了一块,取消了文本原来的形式换行,末尾还有 .
    第二种将原文本形式保留了下来
    第二种的正确的语法结构:

    try:
        f = open('xxx')
    except:
        print 'fail to open'
        exit(-1)
    try:
        do something
    except:
        do something
    finally:
        f.close()

    从这个结构类比:

    set things up
    try:
        do something
    finally:
        tear things down

    这东西是个常见结构,比如文件打开,set things up就表示f=open('xxx')tear things down就表示f.close()。在比如像多线程锁,资源请求,最终都有一个释放的需求。Try…finally结构保证了tear things down这一段永远都会执行,即使上面do something得工作没有完全执行。

    延伸出:with..as语句的来源

    如果经常用这种结构,我们首先可以采取一个较为优雅的办法,封装!

    def controlled_execution(callback):
        set things up
        try:
            callback(thing)
        finally:
            tear things down
     
    def my_function(thing):
        do something
     
    controlled_execution(my_function)

    封装是一个支持代码重用的好办法,但是这个办法很dirty,特别是当do something中有修改一些local variables的时候(变成函数调用,少不了带来变量作用域上的麻烦)。

    另一个办法是使用生成器,但是只需要生成一次数据,我们用for-in结构去调用他:

    def controlled_execution():
        set things up
        try:
            yield thing
        finally:
            tear things down
             
    for thing in controlled_execution():
        do something with thing

    因为thing只有一个,所以yield语句只需要执行一次。当然,从代码可读性也就是优雅的角度来说这简直是糟糕透了。我们在确定for循环只执行一次的情况下依然使用了for循环,这代码给不知道的人看一定很难理解这里的循环是什么个道理。

    最终的python-dev团队的解决方案。(python 2.5以后增加了with表达式的语法)

    class controlled_execution:
        def __enter__(self):
            set things up
            return thing
        def __exit__(self, type, value, traceback):
            tear things down
             
    with controlled_execution() as thing:
            do something

    在这里,python使用了with-as的语法。当python执行这一句时,会调用__enter__函数,然后把该函数return的值传给as后指定的变量。之后,python会执行下面do something的语句块。最后不论在该语句块出现了什么异常,都会在离开时执行__exit__。

    另外,__exit__除了用于tear things down,还可以进行异常的监控和处理,注意后几个参数。要跳过一个异常,只需要返回该函数True即可。下面的样例代码跳过了所有的TypeError,而让其他异常正常抛出。

    def __exit__(self, type, value, traceback):
        return isinstance(value, TypeError)

    在python2.5及以后,file对象已经写好了__enter__和__exit__函数,我们可以这样测试:

    >>> f = open("x.txt")
    >>> f
    <open file 'x.txt', mode 'r' at 0x00AE82F0>
    >>> f.__enter__()
    <open file 'x.txt', mode 'r' at 0x00AE82F0>
    >>> f.read(1)
    'X'
    >>> f.__exit__(None, None, None)
    >>> f.read(1)
    Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
    ValueError: I/O operation on closed file

    之后,我们如果要打开文件并保证最后关闭他,只需要这么做:

    with open("x.txt") as f:
        data = f.read()
        do something with data

    如果有多个项,我们可以这么写:

    with open("x.txt") as f1, open('xxx.txt') as f2:
        do something with f1,f2

    上文说了__exit__函数可以进行部分异常的处理,如果我们不在这个函数中处理异常,他会正常抛出,这时候我们可以这样写(python 2.7及以上版本,之前的版本参考使用contextlib.nested这个库函数):

    1
    2
    3
    4
    5
    try:
        with open( "a.txt" ) as f :
            do something
    except xxxError:
        do something about exception

    总之,with-as表达式极大的简化了每次写finally的工作,这对保持代码的优雅性是有极大帮助的。

  • 相关阅读:
    mybatis中大于等于小于等于的写法
    RandomAccess接口
    ArrayList源码解析
    使用Docker搭建MySQL主从复制(一主一从)
    狂神Docker视频学习笔记(基础篇)
    【JQ】jQuery实现将div中滚动条滚动到指定位置的方法
    JAVA线程池的基本使用
    史上最全的Java技术体系思维导图,没有之一!
    springboot整合kafka
    spring cloud alibaba 分布式事务解决方案之seata-1.3.0
  • 原文地址:https://www.cnblogs.com/jidongdeatao/p/6473291.html
Copyright © 2011-2022 走看看