【问题标题】:How do I check if the archive has only one folder in python?如何检查存档是否在 python 中只有一个文件夹?
【发布时间】:2016-02-19 23:04:11
【问题描述】:

我正在尝试上传一个文件(可以是 tar、tar.gz、bz2 或 zip 之一),在上传之前,我想检查 tar(或任何压缩格式)的内容是否只有文件夹在顶部,名称与变量“name”的名称相同。

在我的代码中,我可以上传文件,但无法检查上述情况。请注意,代码中的 getnames() 不起作用。我们如何检查顶部是否只有一个具有给定名称的文件夹?

请注意,文件夹中可能没有文件。文件夹可能为空。

这是伪代码:

with Archive(fileobj=data['zxc']) as archive:
    if archive.is_archive():
       count=0
       nam=""
       for a in (get names of folders at the top):
           nam=""
           count+=1
           if count!=1:
               print "error"
           elif nam!=name:
               print "error2"
           else:
               print "correct"

【问题讨论】:

标签: python django zip archive tar


【解决方案1】:

文档让我相信这是您的追索权,但我认为 django 中的存档类不支持“zxc”文件。

def has_leading_dir(self, paths):
    """
    Returns true if all the paths have the same leading path name
    (i.e., everything is in one subdirectory in an archive)
    """
    common_prefix = None
    for path in paths:
        prefix, rest = self.split_leading_dir(path)
        if not prefix:
            return False
        elif common_prefix is None:
            common_prefix = prefix
        elif prefix != common_prefix:
            return False
    return True

【讨论】:

  • zxc 是变量名而不是文件名,它可以工作。我在问题中要问的是如何在python中实现问题中提到的伪代码。
  • has_leading_dir 如果顶部有一个没有内容的额外文件夹,可能无法正常工作
猜你喜欢
  • 2010-12-10
  • 2016-06-11
  • 2018-12-26
  • 2018-08-30
  • 2013-03-12
  • 2011-11-15
  • 1970-01-01
  • 2020-02-04
  • 2018-01-15
相关资源
最近更新 更多