Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use list comprehension with list of variable number of filenames?

Given the list of filenames filenames = [...].

Is it possibly rewrite the next list comprehension for I/O-safety: [do_smth(open(filename, 'rb').read()) for filename in filenames]? Using with statement, .close method or something else.

Another problem formulation: is it possibly to write I/O-safe list comprehension for the next code?

results = []
for filename in filenames:
   with open(filename, 'rb') as file:
      results.append(do_smth(file.read()))
like image 953
kupgov Avatar asked Dec 14 '22 04:12

kupgov


1 Answers

You can put the with statement/block to a function and call that in the list comprehension:

def slurp_file(filename):
    with open(filename, 'rb') as f:
        return f.read()

results = [do_smth(slurp_file(f)) for f in filenames]
like image 125
Eugene Yarmash Avatar answered Dec 28 '22 23:12

Eugene Yarmash