简体   繁体   English

将两个python与共享相同代码的语句结合使用

[英]Combine two python with statements that share the same code

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

Question> Is there a better way to combine the above code without duplicating the 'Same Code' section? 问题>有没有更好的方法来组合上面的代码而不重复“相同代码”部分? The function test uses gzip.open if the the file_name is a gz file otherwise it opens with regular open . 如果file_name是gz文件,则函数test使用gzip.open,否则打开常规open

One way would be: 一种方法是:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM