Python - 如何确保资源已关闭

Python - How to make sure resource is closed

我想在从方法返回之前关闭 f。我添加了 finally blocked 但它需要初始化。用什么初始化它?

def test_close_resource(url):
    try:
        f = urllib2.urlopen(url)
        if f.code == 200:
            return True
    except Exception as error:
        return False
    finally:
        f.close()

我认为您要查找的是 with 子句 -

with urllib.request.urlopen('http://python.org/') as response:pass

使用 with 作为上下文管理器打开连接:

import urllib.request
with urllib.request.urlopen('http://www.python.org/') as f:
    print(f.read(300))

连接从使用 with 关键字定义的上下文管理器块出来时自动关闭。