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()))
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With