Skip to content

compression

Transparent compression/decompression of files and streams.

This module provides gzip/bzip2/xz compression helpers operating on any filesystem supported by the gfs layer, plus dispatch helpers - keyed by file extension - and dopen()/copen() context managers which transparently (de)compress the data flowing through the opened streams.

Example
import os
import tempfile

import py_misc_utils.compression as comp


tdir = tempfile.mkdtemp()
src = os.path.join(tdir, 'data.csv')
dest = os.path.join(tdir, 'data.csv.gz')

with open(src, 'w') as fd:
  fd.write('a,b\n1,2\n')

comp.compress(src, dest)
comp.decompress(dest, os.path.join(tdir, 'data.csv'))
assert open(src).read() == open(os.path.join(tdir, 'data.csv')).read()

fgzip(src, dest)

Compresses a file with gzip.

Parameters:

Name Type Description Default
src

The source file path.

required
dest

The destination file path.

required
Example
import os
import tempfile

import py_misc_utils.compression as comp


tdir = tempfile.mkdtemp()
src = os.path.join(tdir, 'f.txt')
dest = os.path.join(tdir, 'f.txt.gz')

with open(src, 'w') as fd:
  fd.write('compress me ' * 200)

comp.fgzip(src, dest)
assert os.path.getsize(dest) < os.path.getsize(src)

back = os.path.join(tdir, 'f_back.txt')
comp.fgunzip(dest, back)
assert open(back).read() == 'compress me ' * 200
Source code in py_misc_utils/compression.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def fgzip(src, dest):
  """Compresses a file with gzip.

  Args:
    src: The source file path.
    dest: The destination file path.

  Example:
    import os
    import tempfile

    import py_misc_utils.compression as comp


    tdir = tempfile.mkdtemp()
    src = os.path.join(tdir, 'f.txt')
    dest = os.path.join(tdir, 'f.txt.gz')

    with open(src, 'w') as fd:
      fd.write('compress me ' * 200)

    comp.fgzip(src, dest)
    assert os.path.getsize(dest) < os.path.getsize(src)

    back = os.path.join(tdir, 'f_back.txt')
    comp.fgunzip(dest, back)
    assert open(back).read() == 'compress me ' * 200
  """
  with (gfs.open(src, mode='rb') as infd, gfs.open(dest, mode='wb') as
        outfd, gzip.open(outfd, mode='wb') as zfd):
    shutil.copyfileobj(infd, zfd)

fgunzip(src, dest)

Decompresses a gzip file.

Parameters:

Name Type Description Default
src

The source file path.

required
dest

The destination file path.

required
Source code in py_misc_utils/compression.py
70
71
72
73
74
75
76
77
78
79
def fgunzip(src, dest):
  """Decompresses a gzip file.

  Args:
    src: The source file path.
    dest: The destination file path.
  """
  with (gfs.open(src, mode='rb') as infd, gfs.open(dest, mode='wb') as
        outfd, gzip.open(infd, mode='rb') as zfd):
    shutil.copyfileobj(zfd, outfd)

fbzip2(src, dest)

Compresses a file with bzip2.

Parameters:

Name Type Description Default
src

The source file path.

required
dest

The destination file path.

required
Example
import os
import tempfile

import py_misc_utils.compression as comp


tdir = tempfile.mkdtemp()
src = os.path.join(tdir, 'f.txt')
dest = os.path.join(tdir, 'f.txt.bz2')

with open(src, 'w') as fd:
  fd.write('bzip2 me ' * 200)

comp.fbzip2(src, dest)
assert os.path.getsize(dest) < os.path.getsize(src)

back = os.path.join(tdir, 'f_back.txt')
comp.fbunzip2(dest, back)
assert open(back).read() == 'bzip2 me ' * 200
Source code in py_misc_utils/compression.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def fbzip2(src, dest):
  """Compresses a file with bzip2.

  Args:
    src: The source file path.
    dest: The destination file path.

  Example:
    import os
    import tempfile

    import py_misc_utils.compression as comp


    tdir = tempfile.mkdtemp()
    src = os.path.join(tdir, 'f.txt')
    dest = os.path.join(tdir, 'f.txt.bz2')

    with open(src, 'w') as fd:
      fd.write('bzip2 me ' * 200)

    comp.fbzip2(src, dest)
    assert os.path.getsize(dest) < os.path.getsize(src)

    back = os.path.join(tdir, 'f_back.txt')
    comp.fbunzip2(dest, back)
    assert open(back).read() == 'bzip2 me ' * 200
  """
  with (gfs.open(src, mode='rb') as infd, gfs.open(dest, mode='wb') as
        outfd, bz2.open(outfd, mode='wb') as zfd):
    shutil.copyfileobj(infd, zfd)

fbunzip2(src, dest)

Decompresses a bzip2 file.

Parameters:

Name Type Description Default
src

The source file path.

required
dest

The destination file path.

required
Source code in py_misc_utils/compression.py
115
116
117
118
119
120
121
122
123
124
def fbunzip2(src, dest):
  """Decompresses a bzip2 file.

  Args:
    src: The source file path.
    dest: The destination file path.
  """
  with (gfs.open(src, mode='rb') as infd, gfs.open(dest, mode='wb') as
        outfd, bz2.open(infd, mode='rb') as zfd):
    shutil.copyfileobj(zfd, outfd)

fxzip(src, dest)

Compresses a file with lzma (xz).

Parameters:

Name Type Description Default
src

The source file path.

required
dest

The destination file path.

required
Example
import os
import tempfile

import py_misc_utils.compression as comp


tdir = tempfile.mkdtemp()
src = os.path.join(tdir, 'f.txt')
dest = os.path.join(tdir, 'f.txt.xz')

with open(src, 'w') as fd:
  fd.write('xz me ' * 200)

comp.fxzip(src, dest)
assert os.path.getsize(dest) < os.path.getsize(src)

back = os.path.join(tdir, 'f_back.txt')
comp.fxunzip(dest, back)
assert open(back).read() == 'xz me ' * 200
Source code in py_misc_utils/compression.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def fxzip(src, dest):
  """Compresses a file with lzma (xz).

  Args:
    src: The source file path.
    dest: The destination file path.

  Example:
    import os
    import tempfile

    import py_misc_utils.compression as comp


    tdir = tempfile.mkdtemp()
    src = os.path.join(tdir, 'f.txt')
    dest = os.path.join(tdir, 'f.txt.xz')

    with open(src, 'w') as fd:
      fd.write('xz me ' * 200)

    comp.fxzip(src, dest)
    assert os.path.getsize(dest) < os.path.getsize(src)

    back = os.path.join(tdir, 'f_back.txt')
    comp.fxunzip(dest, back)
    assert open(back).read() == 'xz me ' * 200
  """
  with (gfs.open(src, mode='rb') as infd, gfs.open(dest, mode='wb') as
        outfd, lzma.open(outfd, mode='wb') as zfd):
    shutil.copyfileobj(infd, zfd)

fxunzip(src, dest)

Decompresses an lzma (xz) file.

Parameters:

Name Type Description Default
src

The source file path.

required
dest

The destination file path.

required
Source code in py_misc_utils/compression.py
160
161
162
163
164
165
166
167
168
169
def fxunzip(src, dest):
  """Decompresses an lzma (xz) file.

  Args:
    src: The source file path.
    dest: The destination file path.
  """
  with (gfs.open(src, mode='rb') as infd, gfs.open(dest, mode='wb') as
        outfd, lzma.open(infd, mode='rb') as zfd):
    shutil.copyfileobj(zfd, outfd)

compressor(ext)

Returns the compressor processor of a file extension.

Parameters:

Name Type Description Default
ext

The file extension - including the leading dot.

required

Returns:

Type Description

A (compressor function, compression module) tuple, or None if the

extension is not supported.

Example
import gzip

import py_misc_utils.compression as comp

proc, module = comp.compressor('.gz')
assert module is gzip
assert comp.compressor('.txt') is None
Source code in py_misc_utils/compression.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def compressor(ext):
  """Returns the compressor processor of a file extension.

  Args:
    ext: The file extension - including the leading dot.

  Returns:
    A (compressor function, compression module) tuple, or None if the
    extension is not supported.

  Example:
    import gzip

    import py_misc_utils.compression as comp

    proc, module = comp.compressor('.gz')
    assert module is gzip
    assert comp.compressor('.txt') is None
  """
  return _COMPRESSORS.get(ext)

decompressor(ext)

Returns the decompressor processor of a file extension.

Parameters:

Name Type Description Default
ext

The file extension - including the leading dot.

required

Returns:

Type Description

A (decompressor function, compression module) tuple, or None if the

extension is not supported.

Example
import lzma

import py_misc_utils.compression as comp

dproc, dmodule = comp.decompressor('.xz')
assert dmodule is lzma
assert comp.decompressor('.bin') is None
Source code in py_misc_utils/compression.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def decompressor(ext):
  """Returns the decompressor processor of a file extension.

  Args:
    ext: The file extension - including the leading dot.

  Returns:
    A (decompressor function, compression module) tuple, or None if the
    extension is not supported.

  Example:
    import lzma

    import py_misc_utils.compression as comp

    dproc, dmodule = comp.decompressor('.xz')
    assert dmodule is lzma
    assert comp.decompressor('.bin') is None
  """
  return _DECOMPRESSORS.get(ext)

compress(src, dest)

Compresses a file, chosen by the destination file extension.

If the destination extension is not supported, the file is copied unchanged.

Parameters:

Name Type Description Default
src

The source file path.

required
dest

The destination file path.

required
Example
import os
import tempfile

import py_misc_utils.compression as comp


tdir = tempfile.mkdtemp()
src = os.path.join(tdir, 'a.bin')
with open(src, 'wb') as fd:
  fd.write(b'x' * 1000)

comp.compress(src, os.path.join(tdir, 'a.bin.bz2'))
comp.compress(src, os.path.join(tdir, 'a.copy.bin'))  # No ext: plain copy.
assert os.path.getsize(os.path.join(tdir, 'a.bin.bz2')) < 1000

comp.decompress(os.path.join(tdir, 'a.bin.bz2'), os.path.join(tdir, 'a2.bin'))
assert open(os.path.join(tdir, 'a2.bin'), 'rb').read() == b'x' * 1000
Source code in py_misc_utils/compression.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def compress(src, dest):
  """Compresses a file, chosen by the destination file extension.

  If the destination extension is not supported, the file is copied
  unchanged.

  Args:
    src: The source file path.
    dest: The destination file path.

  Example:
    import os
    import tempfile

    import py_misc_utils.compression as comp


    tdir = tempfile.mkdtemp()
    src = os.path.join(tdir, 'a.bin')
    with open(src, 'wb') as fd:
      fd.write(b'x' * 1000)

    comp.compress(src, os.path.join(tdir, 'a.bin.bz2'))
    comp.compress(src, os.path.join(tdir, 'a.copy.bin'))  # No ext: plain copy.
    assert os.path.getsize(os.path.join(tdir, 'a.bin.bz2')) < 1000

    comp.decompress(os.path.join(tdir, 'a.bin.bz2'), os.path.join(tdir, 'a2.bin'))
    assert open(os.path.join(tdir, 'a2.bin'), 'rb').read() == b'x' * 1000
  """
  _, ext = os.path.splitext(dest)
  comp = compressor(ext)
  if comp is not None:
    comp.processor(src, dest)
  else:
    shutil.copyfile(src, dest)

decompress(src, dest)

Decompresses a file, chosen by the source file extension.

If the source extension is not supported, the file is copied unchanged.

Parameters:

Name Type Description Default
src

The source file path.

required
dest

The destination file path.

required
Example
import os
import tempfile

import py_misc_utils.compression as comp


tdir = tempfile.mkdtemp()
src = os.path.join(tdir, 'a.bin')
dest = os.path.join(tdir, 'a.bin.xz')
with open(src, 'wb') as fd:
  fd.write(b'y' * 1000)

comp.compress(src, dest)
comp.decompress(dest, os.path.join(tdir, 'a2.bin'))
assert open(os.path.join(tdir, 'a2.bin'), 'rb').read() == b'y' * 1000
Source code in py_misc_utils/compression.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def decompress(src, dest):
  """Decompresses a file, chosen by the source file extension.

  If the source extension is not supported, the file is copied
  unchanged.

  Args:
    src: The source file path.
    dest: The destination file path.

  Example:
    import os
    import tempfile

    import py_misc_utils.compression as comp


    tdir = tempfile.mkdtemp()
    src = os.path.join(tdir, 'a.bin')
    dest = os.path.join(tdir, 'a.bin.xz')
    with open(src, 'wb') as fd:
      fd.write(b'y' * 1000)

    comp.compress(src, dest)
    comp.decompress(dest, os.path.join(tdir, 'a2.bin'))
    assert open(os.path.join(tdir, 'a2.bin'), 'rb').read() == b'y' * 1000
  """
  _, ext = os.path.splitext(src)
  decomp = decompressor(ext)
  if decomp is not None:
    decomp.processor(src, dest)
  else:
    shutil.copyfile(src, dest)

dopen(path, mode='r', **kwargs)

Opens a - possibly compressed - file for reading.

If the file extension is supported, the stream is transparently decompressed; otherwise the plain file is opened.

Parameters:

Name Type Description Default
path

The file path to open.

required
mode

The open mode of the returned stream.

'r'
**kwargs

Keyword arguments passed to gfs.open().

{}

Yields:

Type Description

The open file object.

Example
import os
import tempfile

import py_misc_utils.compression as comp


tdir = tempfile.mkdtemp()
plain = os.path.join(tdir, 'log.txt')
gz = os.path.join(tdir, 'log.txt.gz')

with open(plain, 'w') as fd:
  fd.write('hello world')

comp.fgzip(plain, gz)
with comp.dopen(gz, mode='rt') as fd:
  assert fd.read() == 'hello world'

# Uncompressed files are opened as-is.
with comp.dopen(plain, mode='rt') as fd:
  assert fd.read() == 'hello world'
Source code in py_misc_utils/compression.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
@contextlib.contextmanager
def dopen(path, mode='r', **kwargs):
  """Opens a - possibly compressed - file for reading.

  If the file extension is supported, the stream is transparently
  decompressed; otherwise the plain file is opened.

  Args:
    path: The file path to open.
    mode: The open mode of the returned stream.
    **kwargs: Keyword arguments passed to gfs.open().

  Yields:
    The open file object.

  Example:
    import os
    import tempfile

    import py_misc_utils.compression as comp


    tdir = tempfile.mkdtemp()
    plain = os.path.join(tdir, 'log.txt')
    gz = os.path.join(tdir, 'log.txt.gz')

    with open(plain, 'w') as fd:
      fd.write('hello world')

    comp.fgzip(plain, gz)
    with comp.dopen(gz, mode='rt') as fd:
      assert fd.read() == 'hello world'

    # Uncompressed files are opened as-is.
    with comp.dopen(plain, mode='rt') as fd:
      assert fd.read() == 'hello world'
  """
  _, ext = os.path.splitext(path)

  decomp = decompressor(ext)
  if decomp is None:
    with gfs.open(path, mode=mode, **kwargs) as fd:
      yield fd
  else:
    with (gfs.open(path, mode='rb', **kwargs) as fd, decomp.module.open(fd, mode=mode)
          as zfd):
      yield zfd

copen(path, mode='w', **kwargs)

Opens a - possibly compressed - file for writing.

If the file extension is supported, the written data is transparently compressed; otherwise the plain file is opened.

Parameters:

Name Type Description Default
path

The file path to open.

required
mode

The open mode of the returned stream.

'w'
**kwargs

Keyword arguments passed to gfs.open().

{}

Yields:

Type Description

The open file object.

Example
import os
import tempfile

import py_misc_utils.compression as comp


tdir = tempfile.mkdtemp()
path = os.path.join(tdir, 'out.json.gz')

with comp.copen(path, mode='wt') as fd:
  fd.write('{"key": 1}')

with comp.dopen(path, mode='rt') as fd:
  assert fd.read() == '{"key": 1}'
Source code in py_misc_utils/compression.py
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
@contextlib.contextmanager
def copen(path, mode='w', **kwargs):
  """Opens a - possibly compressed - file for writing.

  If the file extension is supported, the written data is transparently
  compressed; otherwise the plain file is opened.

  Args:
    path: The file path to open.
    mode: The open mode of the returned stream.
    **kwargs: Keyword arguments passed to gfs.open().

  Yields:
    The open file object.

  Example:
    import os
    import tempfile

    import py_misc_utils.compression as comp


    tdir = tempfile.mkdtemp()
    path = os.path.join(tdir, 'out.json.gz')

    with comp.copen(path, mode='wt') as fd:
      fd.write('{"key": 1}')

    with comp.dopen(path, mode='rt') as fd:
      assert fd.read() == '{"key": 1}'
  """
  _, ext = os.path.splitext(path)

  comp = compressor(ext)
  if comp is None:
    with gfs.open(path, mode=mode, **kwargs) as fd:
      yield fd
  else:
    with (gfs.open(path, mode='wb', **kwargs) as fd, comp.module.open(fd, mode=mode) as
          zfd):
      yield zfd