当前位置: 首页>>代码示例>>Python>>正文


Python zipfile.is_zipfile方法代码示例

本文整理汇总了Python中zipfile.is_zipfile方法的典型用法代码示例。如果您正苦于以下问题:Python zipfile.is_zipfile方法的具体用法?Python zipfile.is_zipfile怎么用?Python zipfile.is_zipfile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在zipfile的用法示例。


在下文中一共展示了zipfile.is_zipfile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_compression_type

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def get_compression_type(self, file_path):
        """
        Return compression type assumed by filename

        @param file_path: Path to file
        @type file_path: str | unicode

        @return: compression type, None if no compression
        @rtype: str | None
        """
        assert isinstance(file_path, basestring)
        filename, extension = os.path.splitext(file_path)

        if extension == ".zip" and not zipfile.is_zipfile(file_path):
            return None

        if extension in self._file_extensions_compression:
            return self._file_extensions_compression[extension]
        else:
            return None 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:22,代码来源:compress.py

示例2: load

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def load(cls, file_):
        name = os.path.basename(file_.name)
        backup = Backup(name)
        with open(backup.path, mode='wb') as f:
           try:
               for chunk in file_.chunks():
                   f.write(chunk)
           except AttributeError:
               # file_ as no chunks,
               # read without them.
               while True:
                   content = file_.read(4096)
                   if not content:
                       break
                   f.write(content)
        if not ((name.endswith('.zip') and zipfile.is_zipfile(backup.path))
             or tarfile.is_tarfile(backup.path)
               ):
            os.unlink(backup.path)
            raise ValueError(_("Not a {} file").format(
                                 'zip' if name.endswith('.zip') else 'tar'))
        return backup 
开发者ID:ideascube,项目名称:ideascube,代码行数:24,代码来源:backup.py

示例3: test_export_book_notices

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def test_export_book_notices(staffapp, monkeypatch):
    book1 = BookFactory(isbn="123456", name="my book title")
    name_utf8 = u'النبي (كتاب)'
    BookFactory(isbn="654321", name=name_utf8)
    monkeypatch.setattr(BookExport, 'get_filename', lambda s: 'myfilename')
    resp = staffapp.get(reverse('library:book_export'))
    assert 'myfilename.zip' in resp['Content-Disposition']
    content = ContentFile(resp.content)
    assert zipfile.is_zipfile(content)
    archive = zipfile.ZipFile(content)
    cover_name = '{}.jpg'.format(book1.pk)
    assert cover_name in archive.namelist()
    assert 'myfilename.csv' in archive.namelist()
    assert len(archive.namelist()) == 3
    csv_content = archive.open('myfilename.csv').read().decode('utf-8')
    assert csv_content.startswith(
        'isbn,authors,serie,name,subtitle,description,publisher,section,lang,'
        'cover,tags\r\n')
    assert "my book title" in csv_content
    assert cover_name in csv_content
    assert name_utf8 in csv_content 
开发者ID:ideascube,项目名称:ideascube,代码行数:23,代码来源:test_views.py

示例4: test_create_zipfile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def test_create_zipfile(self):
        # Test to make sure zipfile creation handles common cases.
        # This explicitly includes a folder containing an empty folder.

        dist = Distribution()

        cmd = upload_docs(dist)
        cmd.upload_dir = self.upload_dir
        cmd.target_dir = self.upload_dir
        tmp_dir = tempfile.mkdtemp()
        tmp_file = os.path.join(tmp_dir, 'foo.zip')
        try:
            zip_file = cmd.create_zipfile(tmp_file)

            assert zipfile.is_zipfile(tmp_file)

            zip_file = zipfile.ZipFile(tmp_file) # woh...

            assert zip_file.namelist() == ['index.html']

            zip_file.close()
        finally:
            shutil.rmtree(tmp_dir) 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:25,代码来源:test_upload_docs.py

示例5: _extract_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def _extract_file(self,  file_path, target_folder):
        ark_type = self.ark_type

        if self.ark_type == ArkType.AUTO:
            if tarfile.is_tarfile(file_path):
                ark_type = ArkType.TAR
            elif zipfile.is_zipfile(file_path):
                ark_type = ArkType.ZIP

        if ark_type == ArkType.TAR:
            download.extract_tar(file_path, target_folder)
        elif ark_type == ArkType.ZIP:
            download.extract_zip(file_path, target_folder)
        else:
            raise ValueError(
                'Unrecognized archive type (Only zip/tar supported)!'
            ) 
开发者ID:ynop,项目名称:audiomate,代码行数:19,代码来源:downloader.py

示例6: test_is_zip_erroneous_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def test_is_zip_erroneous_file(self):
        """Check that is_zipfile() correctly identifies non-zip files."""
        # - passing a filename
        with open(TESTFN, "w") as fp:
            fp.write("this is not a legal zip file\n")
        chk = zipfile.is_zipfile(TESTFN)
        self.assertFalse(chk)
        # - passing a file object
        with open(TESTFN, "rb") as fp:
            chk = zipfile.is_zipfile(fp)
            self.assertTrue(not chk)
        # - passing a file-like object
        fp = StringIO()
        fp.write("this is not a legal zip file\n")
        chk = zipfile.is_zipfile(fp)
        self.assertTrue(not chk)
        fp.seek(0, 0)
        chk = zipfile.is_zipfile(fp)
        self.assertTrue(not chk) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:21,代码来源:test_zipfile.py

示例7: test_is_zip_valid_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def test_is_zip_valid_file(self):
        """Check that is_zipfile() correctly identifies zip files."""
        # - passing a filename
        with zipfile.ZipFile(TESTFN, mode="w") as zipf:
            zipf.writestr("foo.txt", "O, for a Muse of Fire!")
        chk = zipfile.is_zipfile(TESTFN)
        self.assertTrue(chk)
        # - passing a file object
        with open(TESTFN, "rb") as fp:
            chk = zipfile.is_zipfile(fp)
            self.assertTrue(chk)
            fp.seek(0, 0)
            zip_contents = fp.read()
        # - passing a file-like object
        fp = StringIO()
        fp.write(zip_contents)
        chk = zipfile.is_zipfile(fp)
        self.assertTrue(chk)
        fp.seek(0, 0)
        chk = zipfile.is_zipfile(fp)
        self.assertTrue(chk) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:23,代码来源:test_zipfile.py

示例8: __init__

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def __init__(self, file):
        self.format = "ooxml"
        file.seek(0)  # TODO: Investigate the effect (required for olefile.isOleFile)
        # olefile cannot process non password protected ooxml files.
        # TODO: this code is duplicate of OfficeFile(). Merge?
        if olefile.isOleFile(file):
            ole = olefile.OleFileIO(file)
            self.file = ole
            with self.file.openstream('EncryptionInfo') as stream:
                self.type, self.info = _parseinfo(stream)
            logger.debug("OOXMLFile.type: {}".format(self.type))
            self.secret_key = None
            if self.type == 'agile':
                # TODO: Support aliases?
                self.keyTypes = ('password', 'private_key', 'secret_key')
            elif self.type == 'standard':
                self.keyTypes = ('password', 'secret_key')
            elif self.type == 'extensible':
                pass
        elif zipfile.is_zipfile(file):
            self.file = file
            self.type, self.info = None, None
            self.secret_key = None
        else:
            raise Exception("Unsupported file format") 
开发者ID:nolze,项目名称:msoffcrypto-tool,代码行数:27,代码来源:ooxml.py

示例9: process_snap

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def process_snap(s, snap, path, quiet=False, unzip=False):
    filename = '{0}_{1}.{2}'.format(snap['sender'], snap['id'],
                                    get_file_extension(snap['media_type']))
    abspath = os.path.abspath(os.path.join(path, filename))
    if os.path.isfile(abspath):
        return
    data = s.get_blob(snap['id'])
    if data is None:
        return
    with open(abspath, 'wb') as f:
        f.write(data)
        if not quiet:
            print('Saved: {0}'.format(abspath))

    if is_zipfile(abspath) and unzip:
        unzip_snap_mp4(abspath, quiet) 
开发者ID:rxw,项目名称:snapy,代码行数:18,代码来源:get_snaps.py

示例10: find_package

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def find_package(self, package):
        for path in self.paths():
            full = os.path.join(path, package)
            if os.path.exists(full):
                return package, full
            if not os.path.isdir(path) and zipfile.is_zipfile(path):
                zip = zipfile.ZipFile(path, 'r')
                try:
                    zip.read(os.path.join(package, '__init__.py'))
                except KeyError:
                    pass
                else:
                    zip.close()
                    return package, full
                zip.close()
        ## FIXME: need special error for package.py case:
        raise InstallationError(
            'No package with the name %s found' % package) 
开发者ID:aliyun,项目名称:oss-ftp,代码行数:20,代码来源:zip.py

示例11: is_archive

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def is_archive(file_path):
        """
        Test if archive can be assumed by filename

        @param file_path: Path to file
        @type file_path: str | unicode

        @return: True if file is archive
        @rtype: str | None
        """
        return tarfile.is_tarfile(file_path) or zipfile.is_zipfile(file_path) 
开发者ID:CAMI-challenge,项目名称:CAMISIM,代码行数:13,代码来源:archive.py

示例12: _unpack_zipfile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def _unpack_zipfile(filename, extract_dir):
    """Unpack zip `filename` to `extract_dir`
    """
    try:
        import zipfile
    except ImportError:
        raise ReadError('zlib not supported, cannot unpack this archive.')

    if not zipfile.is_zipfile(filename):
        raise ReadError("%s is not a zip file" % filename)

    zip = zipfile.ZipFile(filename)
    try:
        for info in zip.infolist():
            name = info.filename

            # don't extract absolute paths or ones with .. in them
            if name.startswith('/') or '..' in name:
                continue

            target = os.path.join(extract_dir, *name.split('/'))
            if not target:
                continue

            _ensure_directory(target)
            if not name.endswith('/'):
                # file
                data = zip.read(info.filename)
                f = open(target, 'wb')
                try:
                    f.write(data)
                finally:
                    f.close()
                    del data
    finally:
        zip.close() 
开发者ID:war-and-code,项目名称:jawfish,代码行数:38,代码来源:shutil.py

示例13: extract_zipped_paths

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def extract_zipped_paths(path):
    """Replace nonexistent paths that look like they refer to a member of a zip
    archive with the location of an extracted copy of the target, or else
    just return the provided path unchanged.
    """
    if os.path.exists(path):
        # this is already a valid path, no need to do anything further
        return path

    # find the first valid part of the provided path and treat that as a zip archive
    # assume the rest of the path is the name of a member in the archive
    archive, member = os.path.split(path)
    while archive and not os.path.exists(archive):
        archive, prefix = os.path.split(archive)
        member = '/'.join([prefix, member])

    if not zipfile.is_zipfile(archive):
        return path

    zip_file = zipfile.ZipFile(archive)
    if member not in zip_file.namelist():
        return path

    # we have a valid zip archive and a valid member of that archive
    tmp = tempfile.gettempdir()
    extracted_path = os.path.join(tmp, *member.split('/'))
    if not os.path.exists(extracted_path):
        extracted_path = zip_file.extract(member, path=tmp)

    return extracted_path 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:32,代码来源:utils.py

示例14: check_format

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def check_format(cls, data):
        '''Validate `data` whether it is in zip format.

        :param data: Data to check.
        :type data: ``bytes``
        :returns: True if it is in zip format else False.
        :rtype: ``bool``
        '''

        return zipfile.is_zipfile(BytesIO(data)) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:12,代码来源:compression.py

示例15: get_fileobj

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def get_fileobj(byte_io: typing.IO[bytes]) -> typing.IO[bytes]:
    """Get a usable file object to read the hosts file from."""
    byte_io.seek(0)  # rewind downloaded file
    if zipfile.is_zipfile(byte_io):
        byte_io.seek(0)  # rewind what zipfile.is_zipfile did
        zf = zipfile.ZipFile(byte_io)
        filename = _guess_zip_filename(zf)
        byte_io = zf.open(filename, mode='r')
    else:
        byte_io.seek(0)  # rewind what zipfile.is_zipfile did
    return byte_io 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:13,代码来源:adblock.py


注:本文中的zipfile.is_zipfile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。