Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

python - will using list comprehension to read a file automagically call close()

Does the following syntax close the file:

lines = [line.strip() for line in open('/somefile/somewhere')]

Bonus points if you can demonstrate how it does or does not...

TIA!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It should close the file, yes, though when exactly it does so is implementation-dependent. The reason is that there is no reference to the open file after the end of the list comprehension, so it will be garbage collected, and that will close the file.

In CPython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpreter, like Jython or Iron Python, there may be a delay.

If you want to be sure your file gets closed, it's much better to use a with statement:

with open("file.txt") as file:
    lines = [line.strip() for line in file]

When the with ends, the file will be closed. This is true even if an exception is raised inside of it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...