1515from os .path import splitext
1616from distutils .version import StrictVersion
1717
18+ from nibabel .optpkg import optional_package
19+
1820# is indexed_gzip present and modern?
1921try :
2022 import indexed_gzip as igzip
3941 IndexedGzipFile = gzip .GzipFile
4042 HAVE_INDEXED_GZIP = False
4143
42- # Enable .zst support if pyzstd installed.
43- try :
44- from pyzstd import ZstdFile
45- HAVE_ZSTD = True
46- except ImportError :
47- HAVE_ZSTD = False
48-
4944
5045def _gzip_open (filename , mode = 'rb' , compresslevel = 9 , keep_open = False ):
5146
@@ -62,6 +57,12 @@ def _gzip_open(filename, mode='rb', compresslevel=9, keep_open=False):
6257 return gzip_file
6358
6459
60+ def _zstd_open (filename , mode = "r" , * , level_or_option = None , zstd_dict = None ):
61+ pyzstd = optional_package ("pyzstd" )[0 ]
62+ return pyzstd .ZstdFile (filename , mode ,
63+ level_or_option = level_or_option , zstd_dict = zstd_dict )
64+
65+
6566class Opener (object ):
6667 r""" Class to accept, maybe open, and context-manage file-likes / filenames
6768
@@ -84,14 +85,13 @@ class Opener(object):
8485 """
8586 gz_def = (_gzip_open , ('mode' , 'compresslevel' , 'keep_open' ))
8687 bz2_def = (BZ2File , ('mode' , 'buffering' , 'compresslevel' ))
88+ zstd_def = (_zstd_open , ('mode' , 'level_or_option' , 'zstd_dict' ))
8789 compress_ext_map = {
8890 '.gz' : gz_def ,
8991 '.bz2' : bz2_def ,
92+ '.zst' : zstd_def ,
9093 None : (open , ('mode' , 'buffering' )) # default
9194 }
92- if HAVE_ZSTD : # add zst to ext map, if library exists
93- zstd_def = (ZstdFile , ('mode' , 'level_or_option' ))
94- compress_ext_map ['.zst' ] = zstd_def
9595 #: default compression level when writing gz and bz2 files
9696 default_compresslevel = 1
9797 #: default option for zst files
0 commit comments