【问题标题】:python, will opened file be closed? [duplicate]python,打开的文件会被关闭吗? [复制]
【发布时间】:2013-01-01 02:13:05
【问题描述】:

可能重复:
Does filehandle get closed automatically in Python after it goes out of scope?

我是 python 新手。我知道如果你打开一个文件并写入它,你需要在最后关闭它。

in_file = open(from_file)
indata = in_file.read()

out_file = open(to_file, 'w')
out_file.write(indata)

out_file.close()
in_file.close()

如果我这样写代码。

open(to_file, 'w').write(open(from_file).read())

我真的不能关闭它,它会自动关闭吗?

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    它将最终关闭,但不能保证何时关闭。当您需要处理此类事情时,最好的方法是使用with 声明:

    with open(from_file) as in_file, open(to_file, "w") as out_file:
        out_file.write(in_file.read())
    
    # Both files are guaranteed to be closed here.
    

    另见:http://preshing.com/20110920/the-python-with-statement-by-example

    【讨论】:

      【解决方案2】:

      Python 垃圾收集器会在销毁文件对象时自动为您关闭文件,但您无法控制实际发生的时间(因此,更大的问题是您不知道是否文件关闭期间发生错误/异常)

      preferred way to do this after Python 2.5 具有with 结构:

      with open("example.txt", 'r') as f:
          data = f.read()
      

      并且该文件保证在您完成后为您关闭,无论发生什么。

      【讨论】:

        【解决方案3】:

        根据http://pypy.org/compat.html,CPython会关闭文件;但是 PyPy 只会在垃圾收集器运行时关闭文件。所以出于兼容性和风格的原因,最好明确关闭文件(或使用with 构造)

        【讨论】:

        • 准确地说,是在 GC 运行或解释器退出时。 CPython 永远不会关闭处于 GC 循环中的文件。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-11
        • 2013-04-11
        • 1970-01-01
        相关资源
        最近更新 更多