How to use list comprehension with a list of variable number of file names?

Given a list of file names filenames = [...].

Is it possible to rewrite the following list comprehension for I / O security [do_smth(open(filename, 'rb').read()) for filename in filenames]:? Using an operator with, method, .closeor something else.

Another problem statement: is it possible to write an I / O-safe list comprehension for the following code?

results = []
for filename in filenames:
   with open(filename, 'rb') as file:
      results.append(do_smth(file.read()))
+4
source share
2 answers

You can put an operator / block within a function and call it in a 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]
+9
source

ExitStack, Python 3.3 :

with ExitStack() as stack:
    files = [stack.enter_context(open(name, "rb")) for name in filenames]
    results = [do_smth(file.read()) for file in files]

, , , , .

+3

Source: https://habr.com/ru/post/1652425/


All Articles