For example I have the following code:
d = [l for l in open('a.txt', 'r')]
After d is created, will the stream opened in the list comprehension get closed automatically ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
“Maybe”.
In cPython, which uses refcounting, the file will be closed as soon as the list comprehension finishes (and all references to the
fileobject are lost).But the Python standard does not require that it be closed. For example, the file will not be closed immediately in jython, which uses the JVM garbage collector.
The “preferred” method of ensuring that resources are correctly closed is the
withstatement:This will guarantee that the file get closed.
And, as @astynax points out, you might be able to use
d = f.readlines()here, as it would have the same semantics as the list comprehension.To prove this to yourself (in cpython):