在 Python 文件对象上使用迭代器时需要 close() [英] Is close() necessary when using iterator on a Python file object

查看:27
本文介绍了在 Python 文件对象上使用迭代器时需要 close()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下操作并且显式处理文件对象并调用其 close() 方法是不好的做法吗?

Is it bad practice to do the following and not explicitly handle a file object and call its close() method?

for line in open('hello.txt'):
    print line

注意 - 这适用于还没有 with 语句的 Python 版本.

NB - this is for versions of Python that do not yet have the with statement.

我问,因为 Python 文档似乎推荐了这个 :-

I ask as the Python documentation seems to recommend this :-

f = open("hello.txt")
try:
    for line in f:
        print line
finally:
    f.close()

这似乎比必要的更冗长.

Which seems more verbose than necessary.

推荐答案

关闭在处理文件时总是是必要的,将打开的文件句柄放在所有地方并不是一个好主意.当文件对象被垃圾回收时,它们最终会被关闭,但你不知道什么时候会发生,同时你会因为持有不再需要的文件句柄而浪费系统资源.

Close is always necessary when dealing with files, it is not a good idea to leave open file handles all over the place. They will eventually be closed when the file object is garbage collected but you do not know when that will be and in the mean time you will be wasting system resources by holding to file handles you no longer need.

如果您使用的是 Python 2.5 及更高版本,可以使用 with 语句自动为您调用 close():

If you are using Python 2.5 and higher the close() can be called for you automatically using the with statement:

from __future__ import with_statement # Only needed in Python 2.5
with open("hello.txt") as f:
    for line in f:
        print line

这与您拥有的代码具有相同的效果:

This is has the same effect as the code you have:

f = open("hello.txt")
try:
    for line in f:
        print line
finally:
    f.close()

with 语句是对资源获取即初始化 C++中常用的成语.它允许安全使用和清理各种资源,例如它可以用于始终确保关闭数据库连接或始终释放锁,如下所示.

The with statement is direct language support for the Resource Acquisition Is Initialization idiom commonly used in C++. It allows the safe use and clean up of all sorts of resources, for example it can be used to always ensure that database connections are closed or locks are always released like below.

mylock = threading.Lock()
with mylock:
    pass # do some thread safe stuff

这篇关于在 Python 文件对象上使用迭代器时需要 close()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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