2

My question looks similar to this one but not sure... I want to parse some log files that are sometimes compressed in gzip sometimes not.

I've got the following:

if file[-3:] == ".gz":
     with gzip.open(file, 'rb') as f:
          # do something
else:
    with open(file) as f:
          # do the same thing.

Is it possible to have only one with statement ?

snoob dogg
  • 2,491
  • 3
  • 31
  • 54

3 Answers3

2
fn = gzip.open if file.endswith('.gz') else open

with fn(file, 'rb') as f:
    ...

Also note that the call to the function returning the context manager does not have to happen inside the with line:

if file.endswith('.gz'):
    ctx = gzip.open(file, 'rb')
else:
    ctx = open(file)

with ctx as f:
    ...
deceze
  • 510,633
  • 85
  • 743
  • 889
1

Put your "Do Something" in a function

def processFile(f)
        Do Something...

if file[-3:] == ".gz":
     with gzip.open(file, 'rb') as f:
          processFile(f)
else:
    with open(file) as f:
          processFile(f)
tomgalpin
  • 1,943
  • 1
  • 4
  • 12
1

You can put the conditional statement in the with line:

with gzip.open(file, 'rb') if file[-3:] == '.gz' else open(file) as f:
   processFile(f)
Jab
  • 26,853
  • 21
  • 75
  • 114