如何在使用 Python 3 解压 tar 文件之前检查它是否不为空?

问题描述 投票:0回答:3

我想解压一些 tar 档案,但我只想处理非空档案。我找到了一些代码

gzip
档案 如何在 Python 中检查空 gzip 文件 还有这个:

async def is_nonempty_tar_file(self, tarfile):
    with open(tarfile, "rb") as f:
        try:
            file_content = f.read(1)
            return len(file_content) > 1
        except Exception as exc:
            self.logger.error(
                f"Reading tarfile failed for {tarfile}", exc_info=True
            )

所有空的和非空的 tar 档案似乎都至少有这个字符

\x1f
。所以即使它们是空的,它们也都通过了测试。

我还能如何检查这个?

python tar tarfile
3个回答
1
投票

您可以使用

tarfile
模块列出 tarfile 的内容:

https://docs.python.org/3/library/tarfile.html#command-line-options

您可能可以使用

tarfile.open
并检查描述符是否包含任何内容。

import tarfile

x = tarfile.open("the_file.tar")
x.list()

1
投票

好的,我找到了一种使用

getmembers()
模块中的
tarfile
方法的方法。我做了这个方法来检查非空 tarfiles:

 def is_nonempty_tar_file(self, archive):
    with tarfile.open(archive, "r") as tar:
        try:
            file_content = tar.getmembers()
            return len(file_content) > 0
        except Exception as exc:
            print(f"Reading tarfile failed for {archive}")

0
投票

如果您想避免列出所有成员(这对于大型 tar 文件可能成本高昂),您还可以检查是否至少有一个成员:

import tarfile

tar = tarfile.open("the_file.tar")

if tar.next() is None:
    print("The tarfile is empty")
else:
    print("The tarfile has at least one member")

至少在我的测试中,这似乎不会影响稍后对

tar.extractall()
的调用,因此
tar.next()
调用似乎不会以影响这一点的方式推进位置,正如名称
next
可能表明的那样.

© www.soinside.com 2019 - 2024. All rights reserved.