我经常看到类似以下的Python代码:
for line in open(filename):
do_something(line)
这段代码中,什么时候会关闭filename文件?
在这种情况下,是否最好写成:
with open(filename) as f:
for line in f.readlines():
do_something(line)
我经常看到类似以下的Python代码:
for line in open(filename):
do_something(line)
这段代码中,什么时候会关闭filename文件?
在这种情况下,是否最好写成:
with open(filename) as f:
for line in f.readlines():
do_something(line)
filename
在作用域之外时将被关闭。这通常是方法的结尾。< /p >
< p > 是的,最好使用 with
。< /p >
Once you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the
close
method on the object, to close the connection to the file:input.close()
In short scripts, people often omit this step, as Python automatically closes the file when a file object is reclaimed during garbage collection (which in mainstream Python means the file is closed just about at once, although other important Python implementations, such as Jython and IronPython, have other, more relaxed garbage collection strategies). Nevertheless, it is good programming practice to close your files as soon as possible, and it is especially a good idea in larger programs, which otherwise may be at more risk of having excessive numbers of uselessly open files lying about. Note that
try
/finally
is particularly well suited to ensuing that a file gets closed, even when a function terminates due to an uncaught exception.
删除 .readlines()
。对于大文件来说这是多余且不可取的(因为会消耗大量内存)。使用'with'
块的变种总是关闭文件。
with open(filename) as file_:
for line in file_:
do_something(line)
在Python的for循环中,文件何时关闭取决于Python的实现方式。
- foosion取决于Python的实现 >> 这可能是不同的人给出不同答案的原因。
with
更好,因为它会在使用后自动关闭文件。甚至不需要使用readlines()
,只需使用for line in file
即可。
我认为第一个示例没有关闭文件。
Python 是一种垃圾回收语言 - CPython 采用引用计数和备用循环检测垃圾收集器。
文件对象在被删除/终止时会关闭其文件句柄。
因此,文件最终将被关闭,并且在 CPython 中将在 for 循环结束时立即关闭。
filename
would be closed…”中指的是f
而不是filename
。 - Andrew Keetonopen(filename)
创建的对象将在其超出范围时关闭,即迭代结束时。 - Esteban Küber