當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。