【问题标题】:How to check if a tar file is not empty before unpacking it with Python 3?如何在使用 Python 3 解包之前检查 tar 文件是否为空?
【发布时间】:2022-01-13 02:18:40
【问题描述】:

我希望解压缩一些 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 档案似乎都至少有 thsi 字符\x1f。所以即使是空的也都通过了测试。

我还能如何检查这个?

【问题讨论】:

  • 如何使用你的命令行工具,比如tar -tvf [tarfile],并检查它是否包含任何东西?
  • 嘿。我想用python,我正在写一个python服务。所以我正在寻找一个 python 工具来做你的建议
  • 你为什么不试着打开它呢?肯定和先检查一样快吗?
  • 因为我想制作一个空列表和一个非空列表

标签: python tar tarfile


【解决方案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()

【讨论】:

  • 我找到了 getmembers() 的方法,但谢谢!
【解决方案2】:

好的,我找到了一种使用 tarfile 模块中的 getmembers() 方法的方法。我做了这个检查非空tarfile的方法:

 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}")

【讨论】:

    猜你喜欢
    • 2014-07-14
    • 2014-10-29
    • 2015-11-17
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2020-03-04
    • 2014-01-01
    • 1970-01-01
    相关资源
    最近更新 更多