我有几个可能的文件可以保存我的数据;它们可以以不同的方式压缩,所以要打开它们我需要使用file()
,gzip.GzipFile()
和其他也返回一个文件对象(支持with
接口)。
我想尝试每一个,直到一个成功打开,所以我可以做类似的事情
try:
with gzip.GzipFile(fn + '.gz') as f:
result = process(f)
except (IOError, MaybeSomeGzipExceptions):
try:
with xCompressLib.xCompressFile(fn + '.x') as f:
result = process(f)
except (IOError, MaybeSomeXCompressExceptions):
try:
with file(fn) as f:
result = process(f)
except IOError:
result = "some default value"
如果我有几十种可能的压缩变体,这显然是不可行的。(嵌套会越来越深,代码总是看起来非常相似。)
有没有更好的方法来拼写这个?
编辑:如果可能的话,我也想process(f)
退出 try/except 以避免意外捕获process(f)
.