Reputation: 35992
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
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
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