for line in open(filename) [英] for line in open(filename)

查看:2577
本文介绍了for line in open(filename)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到类似于

 的开放代码(文件名)中的Python代码:
do_something(line)

文件名何时使用此代码关闭?



  with open(filename)as f:
for line in f。 readlines():
do_something(line)


解决方案

filename 将在关闭范围之后关闭。这通常是方法的结束。



是的,最好用使用


一旦拥有文件对象,就可以通过调用此对象的方法来执行所有文件I / O。 [...]完成文件后,您应该通过调用对象上的关闭方法来完成,以关闭与文件的连接:

  input.close()

简而言之,人们经常忽略这一步,因为Python在垃圾回收期间收回文件对象时自动关闭文件(主流Python意味着文件立即关闭,尽管其他重要的Python实现,例如Jython和IronPython,还有其他更轻松的垃圾收集策略)。然而,尽可能快地关闭文件是很好的编程习惯,而且在较大的程序中尤其是一个好主意,否则可能会出现过多的无用打开文件的风险。请注意,即使函数终止, / finally 特别适合随之而来的关闭文件一个未被捕获的例外。


Python Cookbook,Page


I frequently see python code similar to

for line in open(filename):
    do_something(line)

When does filename get closed with this code?

Would it be better to write

with open(filename) as f:
    for line in f.readlines():
        do_something(line)

解决方案

filename would be closed when it falls out of scope. That normally would be the end of the method.

Yes, it's better to use with.

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.

Python Cookbook, Page 59.

这篇关于for line in open(filename)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆