Reputation: 393
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()))
Upvotes: 4
Views: 372
Reputation: 602115
You can use the ExitStack
introduced in Python 3.3 for this purpose:
with ExitStack() as stack:
files = [stack.enter_context(open(name, "rb")) for name in filenames]
results = [do_smth(file.read()) for file in files]
Note that this opens all the files at once, which is not necessary for this use case, and might not be a good idea if you have a big number of files.
Upvotes: 3
Reputation: 149963
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]
Upvotes: 9