I am building a function that needs to open two type of files (plain text files and .gz files)
I want to use a conditional so I am able to use only one "with open
" statement, instead of having duplicated code.
This is what I do want to achieve (but obviously it does not compile)
if ".gz" in f: # gzipped version of the file, we need gzip.open
with gzip.open(f, "rt") as file:
else:
with open(f,"rt") as file: # normal open
for line in file: # processing of the lines of the file
...
I want to be able to just use one with open, instead of having to create two "with open
" statements with two "for line in file
"
Reason: I want the less amount of code possible.
How can it be done in a Pythonic way?
I would do the opening like this (assign open()
or gzip.open()
functions to variable, based on your filename):
import gzip
f = 'myfile.gz'
opener = open
if ".gz" in f: # gzipped version of the file, we need gzip.open
opener = gzip.open
with opener(f, "rt") as file:
pass # your code