| 1 |
# Copyright (c) 2016, Science and Technology Facilities Council |
| 2 |
# This software is distributed under a BSD licence. See LICENSE.txt. |
| 3 |
""" |
| 4 |
gzipmrcfile |
| 5 |
----------- |
| 6 |
|
| 7 |
Module which exports the :class:`GzipMrcFile` class. |
| 8 |
|
| 9 |
Classes: |
| 10 |
:class:`GzipMrcFile`: An object which represents a gzipped MRC file. |
| 11 |
|
| 12 |
""" |
| 13 |
|
| 14 |
# Import Python 3 features for future-proofing |
| 15 |
from __future__ import (absolute_import, division, print_function, |
| 16 |
unicode_literals) |
| 17 |
|
| 18 |
|
| 19 |
import gzip |
| 20 |
import os |
| 21 |
|
| 22 |
from .mrcfile import MrcFile |
| 23 |
|
| 24 |
|
| 25 |
class GzipMrcFile(MrcFile): |
| 26 |
|
| 27 |
""":class:`~mrcfile.mrcfile.MrcFile` subclass for handling gzipped files. |
| 28 |
|
| 29 |
Usage is the same as for :class:`~mrcfile.mrcfile.MrcFile`. |
| 30 |
|
| 31 |
""" |
| 32 |
|
| 33 |
def __repr__(self): |
| 34 |
return "GzipMrcFile('{0}', mode='{1}')".format(self._fileobj.name, |
| 35 |
self._mode) |
| 36 |
|
| 37 |
def _open_file(self, name): |
| 38 |
"""Override _open_file() to open both normal and gzip files.""" |
| 39 |
self._fileobj = open(name, self._mode + 'b') |
| 40 |
self._iostream = gzip.GzipFile(fileobj=self._fileobj, mode='rb') |
| 41 |
|
| 42 |
def _close_file(self): |
| 43 |
"""Override _close_file() to close both normal and gzip files.""" |
| 44 |
self._iostream.close() |
| 45 |
self._fileobj.close() |
| 46 |
|
| 47 |
def _read(self, header_only=False): |
| 48 |
"""Override _read() to ensure gzip file is in read mode.""" |
| 49 |
self._ensure_readable_gzip_stream() |
| 50 |
super(GzipMrcFile, self)._read(header_only) |
| 51 |
|
| 52 |
def _ensure_readable_gzip_stream(self): |
| 53 |
"""Make sure _iostream is a gzip stream that can be read.""" |
| 54 |
if self._iostream.mode != gzip.READ: |
| 55 |
self._iostream.close() |
| 56 |
self._fileobj.seek(0) |
| 57 |
self._iostream = gzip.GzipFile(fileobj=self._fileobj, mode='rb') |
| 58 |
|
| 59 |
def _get_file_size(self): |
| 60 |
"""Override _get_file_size() to avoid seeking from end.""" |
| 61 |
self._ensure_readable_gzip_stream() |
| 62 |
pos = self._iostream.tell() |
| 63 |
extra = len(self._iostream.read()) |
| 64 |
self._iostream.seek(pos, os.SEEK_SET) |
| 65 |
return pos + extra |
| 66 |
|
| 67 |
def flush(self): |
| 68 |
"""Override :meth:`~mrcfile.mrcinterpreter.MrcInterpreter.flush` since |
| 69 |
GzipFile objects need special handling. |
| 70 |
""" |
| 71 |
if not self._read_only: |
| 72 |
self._iostream.close() |
| 73 |
self._fileobj.seek(0) |
| 74 |
self._iostream = gzip.GzipFile(fileobj=self._fileobj, mode='wb') |
| 75 |
|
| 76 |
# Arrays converted to bytes so gzip can calculate sizes correctly |
| 77 |
self._iostream.write(self.header.tobytes()) |
| 78 |
self._iostream.write(self.extended_header.tobytes()) |
| 79 |
self._iostream.write(self.data.tobytes()) |
| 80 |
self._iostream.flush() |
| 81 |
self._fileobj.truncate() |