将两个python语句与共享相同代码的语句组合在一起
问题>有没有更好的方法可以在不重复“相同代码”部分的情况下组合上述代码?如果将两个python语句与共享相同代码的语句组合在一起,python,python-3.5,Python,Python 3.5,问题>有没有更好的方法可以在不重复“相同代码”部分的情况下组合上述代码?如果文件名是gz文件,则函数测试使用gzip.open,否则它将使用常规的打开打开,其中一种方法是: def test(file_name): if file_name.lower().endswith('.gz'): with gzip.open(file_name) as f: f_csv = csv.reader(i.TextIOWrapper(f))
文件名
是gz文件,则函数测试
使用gzip.open,否则它将使用常规的打开打开,其中一种方法是:
def test(file_name):
if file_name.lower().endswith('.gz'):
with gzip.open(file_name) as f:
f_csv = csv.reader(i.TextIOWrapper(f))
#### Same Code
if file_name.lower().endswith('.csv'):
with open(file_name) as f:
f_csv = csv.reader(i.TextIOWrapper(f))
#### Same Code
只需将####相同的代码
放入(本地)函数中def same_code(f_csv):…
或根据结尾分派文件处理程序,例如将其放入dict或编写自定义分派函数<代码>将自定义打开(文件名)设置为fp:…
可以使用os.path.splitext()而不是重复繁琐的.lower().endswith()。
def test(file_name):
loader = None
if file_name.lower().endswith('.gz'):
loader = gzip.open
elif file_name.lower().endswith('.csv'):
loader = open
if loader is not None:
with loader(file_name) as f:
f_csv = csv.reader(i.TextIOWrapper(f))
#### Same Code
def test(file_name):
f = None
if file_name.lower().endswith('.gz'):
f = gzip.open(file_name)
if file_name.lower().endswith('.csv'):
f = open(file_name)
if f is not None:
f_csv = csv.reader(i.TextIOWrapper(f))
#### Same Code
f.close()