当前位置: 首页>>代码示例>>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方法的21个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: clean_import_zip

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def clean_import_zip(self):
        import_zip = self.cleaned_data.get('import_zip')

        if import_zip:
            if not zipfile.is_zipfile(import_zip.file):
                raise forms.ValidationError("Enter a zip file.")
        return import_zip 
开发者ID:alexsilva,项目名称:openvpn-admin,代码行数:9,代码来源:forms.py


示例17: unpack_file

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def unpack_file(filename, location, content_type, link):
    filename = os.path.realpath(filename)
    if (content_type == 'application/zip' or
            filename.lower().endswith(ZIP_EXTENSIONS) or
            zipfile.is_zipfile(filename)):
        unzip_file(
            filename,
            location,
            flatten=not filename.endswith('.whl')
        )
    elif (content_type == 'application/x-gzip' or
            tarfile.is_tarfile(filename) or
            filename.lower().endswith(
                TAR_EXTENSIONS + BZ2_EXTENSIONS + XZ_EXTENSIONS)):
        untar_file(filename, location)
    elif (content_type and content_type.startswith('text/html') and
            is_svn_page(file_contents(filename))):
        # We don't really care about this
        from pip.vcs.subversion import Subversion
        Subversion('svn+' + link.url).unpack(location)
    else:
        # FIXME: handle?
        # FIXME: magic signatures?
        logger.critical(
            'Cannot unpack file %s (downloaded from %s, content-type: %s); '
            'cannot detect archive format',
            filename, location, content_type,
        )
        raise InstallationError(
            'Cannot determine archive format of %s' % location
        ) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:33,代码来源:__init__.py


示例18: assert_is_zipfile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def assert_is_zipfile(self, path):
        if not zipfile.is_zipfile(path):
            rm(path)
            raise InvalidFile('{} is not a zip file'.format(path)) 
开发者ID:ideascube,项目名称:ideascube,代码行数:6,代码来源:catalog.py


示例19: load_from_ideascube

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def load_from_ideascube(content):
    assert zipfile.is_zipfile(content), _('Not a zip file')
    archive = zipfile.ZipFile(content)
    csv_filename = None
    for name in archive.namelist():
        if name.endswith('.csv'):
            csv_filename = name
            break
    assert csv_filename, _('Missing CSV file in zip')
    csv_content = load_from_zip(archive, csv_filename).decode()
    rows = csv.DictReader(csv_content.splitlines())
    for row in rows:
        cover_filename = row.get('cover')
        if cover_filename:
            cover = ContentFile(load_from_zip(archive, cover_filename),
                                name=cover_filename)
        else:
            cover = None
        notice = {
            'isbn': row.get('isbn'),
            'authors': to_unicode(row.get('authors')),
            'serie': to_unicode(row.get('serie')),
            'name': to_unicode(row.get('name')),
            'subtitle': to_unicode(row.get('subtitle')),
            'description': to_unicode(row.get('description')),
            'publisher': to_unicode(row.get('publisher')),
            'section': to_unicode(row.get('section')),
            'lang': to_unicode(row.get('lang')),
            'tags': to_unicode(row.get('tags')),
        }
        yield notice, cover 
开发者ID:ideascube,项目名称:ideascube,代码行数:33,代码来源:utils.py


示例20: clean_source

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def clean_source(self):
        if not zipfile.is_zipfile(self.cleaned_data['source']):
            raise ValidationError(_('Uploaded file is not a Zip archive'))

        with zipfile.ZipFile(self.cleaned_data['source'].file) as zip:
            for name in zip.namelist():
                if name.endswith('.csv'):
                    self.cleaned_data['csvfilename'] = name
                    break

            else:
                raise ValidationError(_('Archive does not contain a CSV'))

        return self.cleaned_data['source'] 
开发者ID:ideascube,项目名称:ideascube,代码行数:16,代码来源:forms.py


示例21: unpack_zipfile

# 需要导入模块: import zipfile [as 别名]
# 或者: from zipfile import is_zipfile [as 别名]
def unpack_zipfile(filename, extract_dir, progress_filter=default_filter):
    """Unpack zip `filename` to `extract_dir`

    Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
    by ``zipfile.is_zipfile()``).  See ``unpack_archive()`` for an explanation
    of the `progress_filter` argument.
    """

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

    with ContextualZipFile(filename) as z:
        for info in z.infolist():
            name = info.filename

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

            target = os.path.join(extract_dir, *name.split('/'))
            target = progress_filter(name, target)
            if not target:
                continue
            if name.endswith('/'):
                # directory
                ensure_directory(target)
            else:
                # file
                ensure_directory(target)
                data = z.read(info.filename)
                with open(target, 'wb') as f:
                    f.write(data)
            unix_attributes = info.external_attr >> 16
            if unix_attributes:
                os.chmod(target, unix_attributes) 
开发者ID:jpush,项目名称:jbox,代码行数:37,代码来源:archive_util.py



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