Combine two python with operators that use 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

      

Questions> Is there a better way to combine the above code without duplicating the Same Code section? The function test

uses gzip.open if it file_name

is a gz file, otherwise it opens with a regular one open

.

+3


source to share


3 answers


One of the methods:



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

      

+8


source


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

      



0


source


If you want your code to be concise, you can do this:

def test(file_name):
    open_fnc = { '.gz' : gzip.open, '.csv' : open }
    f_csv = csv.reader(i.TextIOWrapper(open_fnc[file_name.lower()[-3:]]() ))

      

Store your functions in a dict and call the correct one by indexing with the filename extension. Note that this will not happen if your file does not have an extension.


If you want to make sure that the absence of an extension doesn't cause an error, you can assign a single default function (say open

) that handles all file types except gzipped.

from collections import defaultdict
def test(file_name):
    open_fnc = defaultdict(open) 
    open_fnc['.gz'] = gzip.open
    f_csv = csv.reader(i.TextIOWrapper(open_fnc[file_name.lower()[-3:]]())) # will invoke `open` for anything besides `.gz` files.

      

0


source







All Articles