【问题标题】:Open file and with statement in Python在 Python 中打开文件和 with 语句
【发布时间】:2013-05-13 01:08:48
【问题描述】:

我有一个类似的功能:

def func(filename):
    with open(filename) as f:
        return [line.split('\t')[0] for line in f]

即使“突然”函数返回,“with”语句是否也会关闭文件?我可以忽略“with”语句吗?即这样做是否安全且等效(从内存泄漏的角度来看),

def func(filename):
    return [line.split('\t')[0] for line in open(filename)]

?

【问题讨论】:

    标签: python


    【解决方案1】:

    很安全。即使您在上下文中 return 也会调用上下文管理器的 __exit__,因此文件句柄已正确关闭。

    这是一个简单的测试:

    class ContextTest(object):
        def __enter__(self):
            print('Enter')
    
        def __exit__(self, type, value, traceback):
            print('Exit')
    
    def test():
        with ContextTest() as foo:
            print('Inside')
            return
    

    当您拨打test() 时,您会得到:

    Enter
    Inside
    Exit
    

    【讨论】:

    • 对不起,我不太清楚,我可以忽略'with'并使用第二种选择吗?
    • @elyase:在这两个示例中都没有内存泄漏,但是您没有在第二个示例中明确关闭文件句柄,这可能会导致问题:stackoverflow.com/questions/4599980/…
    • 很好的例子!您可能想将 ... as test 更改为其他内容,因为您的函数名称也是测试,所以它让我有点停下来。
    【解决方案2】:

    保证这种安全性实际上是with...as... 语法的全部目的;它取代了 try/finally 块,否则会相当尴尬。所以是的,它保证是安全的,这就是为什么我更喜欢with open as f 而不是f = open

    请参阅http://effbot.org/zone/python-with-statement.htm 以获得对语法存在的原因及其工作原理的很好解释。请注意,您可以使用 __enter____exit__ 方法编写自己的类来真正利用这种语法。

    另请参阅此功能的 PEP:http://www.python.org/dev/peps/pep-0343/

    【讨论】:

      猜你喜欢
      • 2018-04-14
      • 2012-03-06
      • 2018-01-27
      • 1970-01-01
      • 2010-10-01
      • 2020-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多