给出文件名列表filenames = [...]
。
是否可能重写下一个I / O安全列表理解:[do_smth(open(filename, 'rb').read()) for filename in filenames]
?使用with
语句,.close
方法或其他方法。
另一个问题表述:是否可能为下一个代码编写I / O安全列表理解?
results = []
for filename in filenames:
with open(filename, 'rb') as file:
results.append(do_smth(file.read()))
答案 0 :(得分:9)
您可以将with
语句/块放到函数中并在列表解析中调用它:
def slurp_file(filename):
with open(filename, 'rb') as f:
return f.read()
results = [do_smth(slurp_file(f)) for f in filenames]
答案 1 :(得分:3)
您可以使用Python 3.3中引入的ExitStack
来实现此目的:
with ExitStack() as stack:
files = [stack.enter_context(open(name, "rb")) for name in filenames]
results = [do_smth(file.read()) for file in files]
请注意,这会立即打开所有文件,这对于此用例不是必需的,如果您有大量文件,则可能不是一个好主意。