对于打开的行(文件名) [英] for line in open(filename)

查看:36
本文介绍了对于打开的行(文件名)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到类似于

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

什么时候文件名会被这段代码关闭?

When does filename get closed with this code?

写出来会更好

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

推荐答案

filename 超出范围时会被关闭.这通常是方法的结束.

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

是的,最好使用 with.

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

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()

在简短的脚本中,人们经常省略这一步,因为 Python 在垃圾回收期间回收文件对象时会自动关闭文件(这在主流 Python 中意味着文件几乎立即关闭,尽管其他重要的 Python 实现,例如如 Jython 和 IronPython,有其他更宽松的垃圾收集策略).尽管如此,尽快关闭文件是一种很好的编程习惯,在较大的程序中尤其是一个好主意,否则可能会有更多无用的打开文件躺在那里的风险.请注意,try/finally 特别适合确保关闭文件,即使函数因未捕获的异常而终止.

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,第 59 页.

这篇关于对于打开的行(文件名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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