1

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,161
  • 1
  • 23
  • 45

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
  • 491,798
  • 79
  • 706
  • 853
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,372
  • 3
  • 11
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
  • 25,138
  • 21
  • 72
  • 111