gpt4 book ai didi

python - 从 .tar-archive 中有效地提取单个文件

转载 作者:太空狗 更新时间:2023-10-30 01:37:58 25 4
gpt4 key购买 nike

我有一个大小为 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 用户非常喜欢的列表理解功能,而是遍历 tar.getmembers()(或在该库中一次给你一个文件的任何东西)并在你遇到问题时中断已经遇到了您想要的结果,而不是将所有文件展开到列表中。

关于python - 从 .tar-archive 中有效地提取单个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29507888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com