代码之家  ›  专栏  ›  技术社区  ›  mevers303

open()是否使文件句柄保持打开状态[[副本]

  •  1
  • mevers303  · 技术社区  · 7 年前

    import json
    _keyfile = json.load(open("s3_key.json", "r"))
    

    如果对它调用.read()呢?

    import json
    _keyfile = json.loads(open("s3_key.json", "r").read())
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   Chris Beard    7 年前

    根据 python docs ,文件将保持打开状态,直到调用 close() 在文件对象上 垃圾收集器为您启动并关闭它。

    with 语句)读取文件时,因为它们将为您关闭文件。

    import json
    with open("s3_key.json", "r") as f:
        _keyfile = json.load(f)
    # f is now closed