python for line in open_for line in open(filename)

可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):

问题:

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)

回答1:

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.

回答2:

The with part is better because it close the file afterwards. You don't even have to use readlines(). for line in file is enough.

I don't think the first one closes it.

回答3:

Drop .readlines(). It is redundant and undesirable for large files (due to memory consumption). The variant with 'with' block always closes file. with open(filename) as file_: for line in file_: do_something(line)

When file will be closed in the bare 'for'-loop variant depends on Python implementation.

回答4:

python is garbage-collected - cpython has reference counting and a backup cycle detecting garbage collector.

File objects close their file handle when the are deleted/finalized.

Thus the file will be eventually closed, and in cpython will closed as soon as the for loop finishes.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值