[英]How to obtain random access of a gzip compressed file
在壓縮流中隨機訪問數據
我知道Biopyton 1.60的Bio.bgzf模塊,其中:
支持讀寫BGZF文件(Blocked GNU Zip Format),這是GZIP的一種變體,具有高效的隨機訪問,最常用作BAM文件格式的一部分和tabix。 它在內部使用Python的zlib庫,並提供一個簡單的接口,如Python的gzip庫。
但對於我的用例,我不想使用那種格式。 基本上我想要一些東西,它模仿下面的代碼:
import gzip
large_integer_new_line_start = 10**9
with gzip.open('large_file.gz','rt') as f:
f.seek(large_integer_new_line_start)
但是本機zlib.net提供的效率可以提供對壓縮流的隨機訪問。 如何利用Python中的隨機訪問功能?
我放棄了使用Python對gzip壓縮文件進行隨機訪問。 相反,我在命令行上使用塊壓縮/解壓縮實用程序將我的gzip壓縮文件轉換為塊gzip壓縮文件:
zcat large_file.gz | bgzip > large_file.bgz
然后我使用BioPython並告訴我獲取bgzipped文件的行號為100萬的virtual_offset。 之后我能夠迅速尋找virtual_offset:
from Bio import bgzf
file='large_file.bgz'
handle = bgzf.BgzfReader(file)
for i in range(10**6):
handle.readline()
virtual_offset = handle.tell()
line1 = handle.readline()
handle.close()
handle = bgzf.BgzfReader(file)
handle.seek(virtual_offset)
line2 = handle.readline()
handle.close()
assert line1==line2
我還想指出Mark Adler在zlib發行版中的examples / zran.c上的回答 。
您正在尋找dictzip.py
,它是serpento軟件包的一部分。 但是,您必須使用dictzip
壓縮文件,這是gzip
壓縮的隨機可搜索向后兼容變體。
indexed_gzip程序可能就是你想要的。 它還使用zran.c
下的zran.c
如果您只是想從隨機點訪問該文件,您不能這樣做:
from random import randint
with open(filename) as f:
f.seek(0, 2)
size = f.tell()
f.seek(randint(0, size), 2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.