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

svmlkihl  于 12个月前  发布在  Python
关注(0)|答案(3)|浏览(122)

我希望解压缩一些tar档案,但我只想rpcess非空的。我发现了一些gzip存档How to check empty gzip file in Python的代码,还有这个:

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。所以他们都通过了测试,即使他们是空的。
我还能怎么检查这个?

4ioopgfo

4ioopgfo1#

您可以使用tarfile模块列出tarfiles的内容:
https://docs.python.org/3/library/tarfile.html#command-line-options
您可能只需要使用tarfile.open并检查描述符是否包含任何内容。

import tarfile

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

agxfikkp2#

好的,我找到了一个方法,使用tarfile模块中的getmembers()方法。我做了这个方法来检查非空的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}")
wyyhbhjk

wyyhbhjk3#

如果你想避免列出所有成员(这在一个大的tarfile上可能会很昂贵),你也可以检查是否至少有一个成员:

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可能表明的那样。

相关问题