python,打开的文件会被关闭吗?

python,打开的文件会被关闭吗?,python,python-2.7,Python,Python 2.7,可能重复: 我是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新手。我知道如果你打开并写入一个文件,你需要在最后关闭它

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())
我真的无法关闭它,它会自动关闭吗?

它最终会关闭,但无法保证何时关闭。当您需要处理此类事情时,最好的方法是声明:

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.
另请参见:

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

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.

另请参见:

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

具有
结构:

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

而且,无论发生什么情况,文件都保证在您处理完后为您关闭。

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

具有
结构:

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

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

根据,CPython将关闭该文件;但是PyPy仅在垃圾收集器运行时关闭该文件。因此,出于兼容性和样式原因,最好显式关闭该文件(或将
构造一起使用)

根据,CPython将关闭文件;但是PyPy将仅在垃圾收集器运行时关闭文件。因此,出于兼容性和样式原因,最好显式关闭文件(或将
构造一起使用)

准确地说,当GC运行或解释器退出时。CPython永远不会关闭GC循环中的文件。准确地说,当GC运行或解释器退出时。CPython永远不会关闭GC循环中的文件。