Open file and with statement in Python -


i have function like:

def func(filename):     open(filename) f:         return [line.split('\t')[0] line in f] 

is "with" statement closing file when there 'sudden' function return? can ignore "with" statement? i.e. safe , equivalent (from memory leak perspective) do,

def func(filename):     return [line.split('\t')[0] line in open(filename)] 

?

it's safe. context manager's __exit__ called if return while inside of context, file handle closed.

here's simple test:

class contexttest(object):     def __enter__(self):         print('enter')      def __exit__(self, type, value, traceback):         print('exit')  def test():     contexttest() foo:         print('inside')         return 

when call test(), get:

enter inside exit 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -