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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With