Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 814
q0987 Avatar asked Sep 24 '26 11:09

q0987


1 Answers

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
like image 53
freakish Avatar answered Sep 26 '26 01:09

freakish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!