Search code examples
pythonpython-3.xfile-iolist-comprehensioncontextmanager

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()))

Solution

  • 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]