Add tabix gzip detection instead of assuming based on filename.  Also add option to leave original file when compressing.
# DEALINGS IN THE SOFTWARE.
#
###############################################################################
+import binascii
import os
import sys
@@ -843,6 +844,13 @@ def tabix_compress(filename_in,
raise IOError("error %i when closing file %s" % (r, filename_in))
+def is_gzip_file(filename):
+ gzip_magic_hex = b'1f8b'
+ fd = os.open(filename, os.O_RDONLY)
+ header = os.read(fd, 2)
+ return header == binascii.a2b_hex(gzip_magic_hex)
+
+
def tabix_index(filename,
force=False,
seq_col=None,
@@ -850,10 +858,10 @@ def tabix_index(filename,
end_col=None,
preset=None,
meta_char="#",
- int line_skip=0,
zerobased=False,
int min_shift=-1,
index=None,
+ keep_original=False,
):
'''index tab-separated *filename* using tabix.
@@ -878,12 +886,9 @@ def tabix_index(filename,
Lines beginning with *meta_char* and the first *line_skip* lines
will be skipped.
- If *filename* does not end in ".gz", it will be automatically
- compressed. The original file will be removed and only the
- compressed file will be retained.
-
- If *filename* ends in *gz*, the file is assumed to be already
- compressed with bgzf.
+ If *filename* is not detected as a gzip file it will be automatically
+ compressed. The original file will be removed and only the compressed
+ file will be retained.
*min-shift* sets the minimal interval size to 1<<INT; 0 for the
old tabix index. The default of -1 is changed inside htslib to
@@ -892,8 +897,10 @@ def tabix_index(filename,
*index* controls the filename which should be used for creating the index.
If not set, the default is to append ``.tbi`` to *filename*.
- returns the filename of the compressed data
+ When automatically compressing files, if *keep_original* is set the
+ uncompressed file will not be deleted.
+ returns the filename of the compressed data
'''
if not os.path.exists(filename):
@@ -904,8 +911,9 @@ def tabix_index(filename,
raise ValueError(
"neither preset nor seq_col,start_col and end_col given")
- if not filename.endswith(".gz"):
+ if not is_gzip_file(filename):
tabix_compress(filename, filename + ".gz", force=force)
+ if not keep_original:
os.unlink( filename )
filename += ".gz"
