Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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!

like image 514
bitfish Avatar asked Sep 17 '13 03:09

bitfish


People also ask

What is the advantage of use list comprehension in Python?

One main benefit of using a list comprehension in Python is that it's a single tool that you can use in many different situations. In addition to standard list creation, list comprehensions can also be used for mapping and filtering. You don't have to use a different approach for each scenario.

What are list comprehensions used for?

List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.

How does list comprehension work in Python?

List comprehensions provide us with a simple way to create a list based on some sequence or another list that we can loop over. In python terminology, anything that we can loop over is called iterable. At its most basic level, list comprehension is a syntactic construct for creating lists from existing lists.

Which is faster for loop or list comprehension?

List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.


2 Answers

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.

like image 102
Blckknght Avatar answered Sep 16 '22 16:09

Blckknght


This is how you should do it

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

In CPython the file should be closed right away as there are no references to it left, but Python language does not guarantee this.

In Jython, the file won't be closed until the garbage collector runs

like image 25
John La Rooy Avatar answered Sep 17 '22 16:09

John La Rooy