如何检查存档在python中只有一个文件夹?

时间:2022-08-04 07:28:23

I am trying to upload a file(which can be one of tar,tar.gz,bz2 or zip) and before uploading it, I want to check that the contents of the tar (or any compressed format) has only folder at the top with a name same as that of the variable 'name'.

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

In my code, I am able to upload the file but I am not able to check the above condition. Please note that getnames() in the code does not work. How do we check that there is only one folder at the top with a given name?

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

Please note that the folders may have no files inside them. The folders may be empty.

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

Here is the pseudo code:

这是伪代码:

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"

1 个解决方案

#1


0  

The docs lead me to believe this is your recourse, but I do not think 'zxc' files are supported by the archive class in django.

文档让我相信这是你的追索权,但我不认为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

#1


0  

The docs lead me to believe this is your recourse, but I do not think 'zxc' files are supported by the archive class in django.

文档让我相信这是你的追索权,但我不认为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