Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将两个python语句与共享相同代码的语句组合在一起_Python_Python 3.5 - Fatal编程技术网

将两个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()