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
.
source to share
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.
source to share