簡體   English   中英

從.tar-archive有效地提取單個文件

[英]Efficiently extract single file from .tar-archive

我有一個大小為2GB的.tgz文件。

我想從.tgz文件中只提取一個大小為2KB的.txt文件。

我有以下代碼:

import tarfile
from contextlib import closing

with closing(tarfile.open("myfile.tgz")) as tar:
    subdir_and_files = [
        tarinfo for tarinfo in tar.getmembers()
        if tarinfo.name.startswith("myfile/first/second/text.txt")
        ]
    print subdir_and_files
    tar.extractall(members=subdir_and_files)

問題是我得到提取的文件至少需要一分鍾。 似乎extractall提取所有文件,但只保存我問的那個。

有沒有更有效的方法來實現它?

沒有。

tar格式不適合快速提取單個文件。 在大多數情況下,這種情況會惡化,因為tar文件通常是壓縮流。 我建議7z。

是的,有點兒。

如果您知道只有一個文件具有該名稱,或者您只想要一個文件,則可以在第一次命中后中止提取過程。

例如

完全掃描東西。

$ time tar tf /var/log/apache2/old/2016.tar.xz 
2016/
2016/access.log-20161023
2016/access.log-20160724
2016/ssl_access.log-20160711
2016/error.log-20160815
(...)
2016/error.log-20160918
2016/ssl_request.log-20160814
2016/access.log-20161017
2016/access.log-20160516
time: Real 0m1.5s  User 0m1.4s  System 0m0.2s

從內存中掃描東西

$ time tar tf /var/log/apache2/old/2016.tar.xz  > /dev/null 
time: Real 0m1.3s  User 0m1.2s  System 0m0.2s

在第一個文件后中止

$ time tar tf /var/log/apache2/old/2016.tar.xz  | head -n1 
2016/
time: Real 0m0.0s  User 0m0.0s  System 0m0.0s

三個文件后中止

$ time tar tf /var/log/apache2/old/2016.tar.xz  | head -n3 
2016/
2016/access.log-20161023
2016/access.log-20160724
time: Real 0m0.0s  User 0m0.0s  System 0m0.0s

在“中間”的一些文件后中止

$ time tar xf /var/log/apache2/old/2016.tar.xz  2016/access.log-20160724  | head -n1 
time: Real 0m0.9s  User 0m0.9s  System 0m0.1s

在“底部”的一些文件后中止

$ time tar xf /var/log/apache2/old/2016.tar.xz  2016/access.log-20160516  | head -n1 
time: Real 0m1.1s  User 0m1.1s  System 0m0.2s

我在這里向你展示,如果你通過退出第一行(head -n1)后退出GNU tar的輸出管道(標准輸出),那么tar進程也會死掉。

您可以看到,讀取整個存檔需要的時間比在存檔附近的某個文件接近中止后的中止時間要長。 您還可以看到在頂部遇到文件后中止讀取所花費的時間要少得多。

如果我可以決定存檔的格式,我不會這樣做。


秀...

而不是python-people喜歡這樣的列表理解的東西,迭代tar.getmembers() (或者在該庫中一次給你一個文件的任何東西)並在你遇到你想要的結果時中斷,而不是擴展所有的文件到列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM