Skip to content

uncompress

Decompression of files into temporary storage.

This module provides a context manager which transparently decompresses a compressed file, exposing the decompressed content for the duration of the context.

Example
import gzip
import os
import tempfile

import py_misc_utils.uncompress as unc


tdir = tempfile.mkdtemp()
gz = os.path.join(tdir, 'data.csv.gz')
with gzip.open(gz, 'wt') as fd:
  fd.write('x,y\n1,2\n')

with unc.Uncompress(gz) as path:
  assert os.path.basename(path) == 'data.csv'
  assert open(path).read() == 'x,y\n1,2\n'

Uncompress

Context manager which decompresses a file on entry.

If the file has a recognized compression extension, its content is decompressed into a temporary directory and the decompressed path is returned by the context; otherwise the original path is returned unchanged. The temporary files are removed on exit.

Example
import os
import tempfile

import py_misc_utils.uncompress as unc


tdir = tempfile.mkdtemp()
plain = os.path.join(tdir, 'plain.txt')
with open(plain, 'w') as fd:
  fd.write('not compressed')

with unc.Uncompress(plain) as path:
  assert path == plain
Source code in py_misc_utils/uncompress.py
 32
 33
 34
 35
 36
 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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class Uncompress:
  """Context manager which decompresses a file on entry.

  If the file has a recognized compression extension, its content is
  decompressed into a temporary directory and the decompressed path is
  returned by the context; otherwise the original path is returned
  unchanged. The temporary files are removed on exit.

  Example:
    import os
    import tempfile

    import py_misc_utils.uncompress as unc


    tdir = tempfile.mkdtemp()
    plain = os.path.join(tdir, 'plain.txt')
    with open(plain, 'w') as fd:
      fd.write('not compressed')

    with unc.Uncompress(plain) as path:
      assert path == plain
  """

  def __init__(self, path):
    """Initialize the decompression context.

    Args:
      path: Path of the file which may be compressed.
    """
    self._path = path
    self._tempdir = None

  def __enter__(self):
    """Decompress the file, returning the path to its content.

    Returns:
      The path of the decompressed file in a temporary directory, or the
      original path when the file is not compressed.
    """
    bpath, ext = os.path.splitext(self._path)

    decomp = comp.decompressor(ext)
    if decomp is not None:
      self._tempdir = tempfile.mkdtemp()
      rpath = os.path.join(self._tempdir, os.path.basename(bpath))

      try:
        decomp.processor(self._path, rpath)
        shutil.copystat(self._path, rpath)
      except Exception:
        shutil.rmtree(self._tempdir, ignore_errors=True)
        self._tempdir = None
        raise
    else:
      rpath = self._path

    return rpath

  def __exit__(self, *exc):
    """Remove any temporary decompression directory.

    Args:
      *exc: Exception information of the context (ignored).

    Returns:
      False, so that exceptions are propagated.
    """
    if self._tempdir is not None:
      shutil.rmtree(self._tempdir, ignore_errors=True)

    return False