q0987
q0987

Reputation: 35992

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.

Upvotes: 3

Views: 112

Answers (2)

BoilingFire
BoilingFire

Reputation: 309

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

Upvotes: 0

freakish
freakish

Reputation: 56547

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

Upvotes: 8

Related Questions