【发布时间】:2014-10-29 10:00:42
【问题描述】:
我有文件,读取时它们的格式完全相同,但唯一的区别是我不确定其中一些文件是否为gzip。
示例文件如下:
der ||| the ||| 0.3 ||| |||
das ||| the ||| 0.4 ||| |||
das ||| it ||| 0.1 ||| |||
das ||| this ||| 0.1 ||| |||
die ||| the ||| 0.3 ||| |||
当我读到它时,我正在这样做:
try:
with gzip.open(phrasetablefile, 'rb') as fin:
for line in fin:
# do something
except:
with open(phrasetablefile, 'rb') as fin:
for line in fin:
# do something
有没有其他方法可以避免丑陋的重复代码?(注意 #do something 是一段很长的代码)
有没有办法做到以下几点?
try:
with gzip.open(phrasetablefile, 'rb') as fin:
except:
with open(phrasetablefile, 'rb') as fin:
for line in fin:
# do something
【问题讨论】:
-
为什么不把它拉到一个函数中,例如
process,那么就只有process(fin)?另外,至少应该是except Exception。 -
@jonrsharpe,智慧之言。
标签: python file-io compression gzip