我想解压缩一些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
。所以它们都通过了测试,即使它们是空的。
我还能怎么查?
您可以使用tarfile
模块列出tarfile的内容:
https://docs.python.org/3/library/tarfile.html#command-线路选项
您可能只需要使用tarfile.open
并检查描述符是否包含任何内容。
import tarfile
x = tarfile.open("the_file.tar")
x.list()
好的,我从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}")