逐行文件处理,for-loop vs [英] line-by-line file processing, for-loop vs with
问题描述
我试图理解这些交易的差异/
之间的差异,以逐行处理的方式打开文件
with open('data.txt')as inf:
for line in $:
#etc
对于open('data.txt')中的行:
$ etc
我明白,使用和
确保当
with-block(suite?)被退出(或异常被反击)时文件被关闭。所以我一直在使用和
,因为我在这里了解到了它。
Re for
-loop:从网上搜索到SO,似乎当 -loop -loop退出时,是否关闭文件
依赖于实现吗?而
我找不到有关这个构造如何处理
异常的任何事情。有人知道吗?
如果我误解了上面的任何内容,我会感谢更正
,否则有理由永远使用 for
通过
来构造
? (假设你有一个选择,即不受Python版本限制)
用于打开('data.txt')行:
#etc
是不是你打开的文件保留一个明确的引用,那么你怎样关闭它?
懒惰的方式是等待垃圾收集器清理它,但这可能意味着资源不能及时释放。
所以你可以说:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ #etc
inf.close()
现在如果发生异常在for循环里面?
添加 try / finally
inf = open('data.txt')
尝试:
在inf中的行:
#etc
finally:
inf.close()
这是很多代码非常简单,所以Python用添加来使这个代码能够以更可读的方式写入。我们来到这里
with open('data.txt')as inf:
for line in inf:
#etc
所以,这是打开文件的首选方式。如果你的Python对于with语句来说太老了,你应该使用 try / finally
版本来生产代码
I am trying to understand the trade offs/differences between these to ways of opening files for line-by-line processing
with open('data.txt') as inf:
for line in inf:
#etc
vs
for line in open('data.txt'):
# etc
I understand that using with
ensures the file is closed when the
"with-block" (suite?) is exited (or an exception is countered). So I have been using with
ever since I learned about it here.
Re for
-loop: From searching around the net and SO, it seems that whether the file
is closed when the for
-loop is exited is implementation dependent? And
I couldn't find anything about how this construct would deal with
exceptions. Does anyone know?
If I am mistaken about anything above, I'd appreciate corrections,
otherwise is there a reason to ever use the for
construct over the
with
? (Assuming you have a choice, i.e., aren't limited by Python version)
The problem with this
for line in open('data.txt'):
# etc
Is that you don't keep an explicit reference to the open file, so how do you close it? The lazy way is wait for the garbage collector to clean it up, but that may mean that the resources aren't freed in a timely manner.
So you can say
inf = open('data.txt')
for line in inf:
# etc
inf.close()
Now what happens if there is an exception while you are inside the for loop? The file won't get closed explicitly.
Add a try/finally
inf = open('data.txt')
try:
for line in inf:
# etc
finally:
inf.close()
This is a lot of code to do something pretty simple, so Python added with
to enable this code to be written in a more readable way. Which gets us to here
with open('data.txt') as inf:
for line in inf:
#etc
So, that is the preferred way to open the file. If your Python is too old for the with statement, you should use the try/finally
version for production code
这篇关于逐行文件处理,for-loop vs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!