當前位置: 首頁>>代碼示例>>Python>>正文


Python zipfile.BadZipfile方法代碼示例

本文整理匯總了Python中zipfile.BadZipfile方法的典型用法代碼示例。如果您正苦於以下問題:Python zipfile.BadZipfile方法的具體用法?Python zipfile.BadZipfile怎麽用?Python zipfile.BadZipfile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在zipfile的用法示例。


在下文中一共展示了zipfile.BadZipfile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: Run

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def Run(self):
    try:
      zip_file = self._args[0]
      out_path = self._args[1]
    except IndexError:
      raise ActionError('Unable to determine desired paths from %s.' %
                        str(self._args))

    try:
      file_util.CreateDirectories(out_path)
    except file_util.Error:
      raise ActionError('Unable to create output path %s.' % out_path)

    try:
      zf = zipfile.ZipFile(zip_file)
      zf.extractall(out_path)
    except (IOError, zipfile.BadZipfile) as e:
      raise ActionError('Bad zip file given as input.  %s' % e) 
開發者ID:google,項目名稱:glazier,代碼行數:20,代碼來源:files.py

示例2: open

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def open(self, filename):
        try:
            if self.zipmode:
                if self.verbose:
                    print( "Opening Zip archive "+filename)
                self.handle = zipfile.ZipFile(filename, 'r')
            else:
                if self.verbose:
                    print( "Opening Rar archive "+filename)
                self.handle = rarfile.RarFile(filename, 'r')

        except (struct.error, zipfile.BadZipfile, zipfile.LargeZipFile, IOError) as e:
            if self.verbose:
                print( "Exception caught in ZipFile: %s" % (repr(e)))
            self.handle = None

        return self.handle 
開發者ID:cryptax,項目名稱:droidlysis,代碼行數:19,代碼來源:droidziprar.py

示例3: check_read_with_bad_crc

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def check_read_with_bad_crc(self, compression):
        """Tests that files with bad CRCs raise a BadZipfile exception when read."""
        zipdata = self.zips_with_bad_crc[compression]

        # Using ZipFile.read()
        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            self.assertRaises(zipfile.BadZipfile, zipf.read, 'afile')

        # Using ZipExtFile.read()
        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            with zipf.open('afile', 'r') as corrupt_file:
                self.assertRaises(zipfile.BadZipfile, corrupt_file.read)

        # Same with small reads (in order to exercise the buffering logic)
        with zipfile.ZipFile(io.BytesIO(zipdata), mode="r") as zipf:
            with zipf.open('afile', 'r') as corrupt_file:
                corrupt_file.MIN_READ_SIZE = 2
                with self.assertRaises(zipfile.BadZipfile):
                    while corrupt_file.read(2):
                        pass 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:22,代碼來源:test_zipfile.py

示例4: main

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def main():
    """
    Read input zip file, minhash the documents in it and put them in buckets
    The zip file should have been created with data_prep/prepare_blobstore_zips
    """
    try:
        filename = os.path.abspath(sys.argv[1])
    except IndexError:
        print 'filename not provided'
        exit(1)
    try:
        zip_reader = zipfile.ZipFile(filename)
    except IOError:
        print 'unable to read file {file}'.format(file = filename)
        exit(1)
    except zipfile.BadZipfile:
        print 'file {file} is not a zip file'.format(file = filename)
        exit(1)

    lsh_zipfile(PeerbeltLine, zip_reader, 'bash', filename) 
開發者ID:singhj,項目名稱:locality-sensitive-hashing,代碼行數:22,代碼來源:serial.py

示例5: _create_cbz_

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def _create_cbz_(dirpath, archivename):
        """
        Create a Comic Book Archive in .cbz and .cbr format (Tar Compression)

        :param dirpath: Directory location to save the the book archive.
        :param archivename: Name of the archive.
        """
        currdir = os.getcwd()
        try:
            import zlib

            compression = zipfile.ZIP_DEFLATED
        except ImportError:
            logging.warning("zlib library not available. Using ZIP_STORED compression.")
            compression = zipfile.ZIP_STORED
        try:
            with zipfile.ZipFile(archivename, "w", compression) as zf:
                os.chdir(os.path.abspath(os.path.join(dirpath, os.pardir)))
                name = os.path.basename(dirpath)
                for file in os.listdir(name):
                    zf.write(os.path.join(name, file))
        except zipfile.BadZipfile:
            logging.error("Unable to compile CBR file ")
        os.chdir(currdir) 
開發者ID:AnimeshShaw,項目名稱:MangaScrapper,代碼行數:26,代碼來源:mangascrapper.py

示例6: _extract

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def _extract(self, filename, password):
        archive_path = _prepare_archive_at_path(filename)
        if not archive_path:
            return None
        # Extraction.
        extract_path = environ.get("TEMP", "/tmp")
        with ZipFile(archive_path, "r") as archive:
            try:
                archive.extractall(path=extract_path, pwd=password)
            except BadZipfile:
                raise Exception("Invalid Zip file")
            # Try to extract it again, but with a default password
            except RuntimeError:
                try:
                    archive.extractall(path=extract_path, pwd="infected")
                except RuntimeError as err:
                    raise Exception("Unable to extract Zip file: %s" % err)
            finally:
                self._extract_nested_archives(archive, extract_path, password)
        return archive.namelist() 
開發者ID:phdphuc,項目名稱:mac-a-mal-cuckoo,代碼行數:22,代碼來源:zip.py

示例7: _prepare_archive_at_path

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def _prepare_archive_at_path(filename):
    """ Verifies that there's a readable zip archive at the given path.

    This function returns a new name for the archive (for most cases it's
    the same as the original one; but if an archive named "foo.zip" contains
    a file named "foo" this archive will be renamed to avoid being overwrite.
    """
    # Verify that the archive is actually readable
    try:
        with ZipFile(filename, "r") as archive:
            archive.close()
    except BadZipfile:
        return None
    # Test if zip file contains a file named as itself
    if _is_overwritten(filename):
        log.debug("ZIP file contains a file with the same name, original is \
        going to be overwrite")
        # In this case we just change the file name
        new_zip_path = filename + _random_extension()
        move(filename, new_zip_path)
        filename = new_zip_path
    return filename 
開發者ID:phdphuc,項目名稱:mac-a-mal-cuckoo,代碼行數:24,代碼來源:zip.py

示例8: _makeArchive

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def _makeArchive(self, buffer: "io.BytesIO", root_path: str) -> Optional[ZipFile]:
        """Make a full archive from the given root path with the given name.

        :param root_path: The root directory to archive recursively.
        :return: The archive as bytes.
        """

        ignore_string = re.compile("|".join(self.IGNORED_FILES))
        try:
            archive = ZipFile(buffer, "w", ZIP_DEFLATED)
            for root, folders, files in os.walk(root_path):
                for item_name in folders + files:
                    absolute_path = os.path.join(root, item_name)
                    if ignore_string.search(absolute_path):
                        continue
                    archive.write(absolute_path, absolute_path[len(root_path) + len(os.sep):])
            archive.close()
            return archive
        except (IOError, OSError, BadZipfile) as error:
            Logger.log("e", "Could not create archive from user data directory: %s", error)
            self._showMessage(
                self.catalog.i18nc("@info:backup_failed",
                                   "Could not create archive from user data directory: {}".format(error)))
            return None 
開發者ID:Ultimaker,項目名稱:Cura,代碼行數:26,代碼來源:Backup.py

示例9: test_invalidHeader

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def test_invalidHeader(self):
        """
        A zipfile entry with the wrong magic number should raise BadZipfile for
        readfile(), but that should not affect other files in the archive.
        """
        fn = self.makeZipFile(["test contents",
                               "more contents"])
        with zipfile.ZipFile(fn, "r") as zf:
            zeroOffset = zf.getinfo("0").header_offset
        # Zero out just the one header.
        with open(fn, "r+b") as scribble:
            scribble.seek(zeroOffset, 0)
            scribble.write(b'0' * 4)
        with zipstream.ChunkingZipFile(fn) as czf:
            self.assertRaises(zipfile.BadZipfile, czf.readfile, "0")
            with czf.readfile("1") as zfe:
                self.assertEqual(zfe.read(), b"more contents") 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:19,代碼來源:test_zipstream.py

示例10: test_filenameMismatch

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def test_filenameMismatch(self):
        """
        A zipfile entry with a different filename than is found in the central
        directory should raise BadZipfile.
        """
        fn = self.makeZipFile([b"test contents",
                               b"more contents"])
        with zipfile.ZipFile(fn, "r") as zf:
            info = zf.getinfo("0")
            info.filename = "not zero"
        with open(fn, "r+b") as scribble:
            scribble.seek(info.header_offset, 0)
            scribble.write(info.FileHeader())

        with zipstream.ChunkingZipFile(fn) as czf:
            self.assertRaises(zipfile.BadZipfile, czf.readfile, "0")
            with czf.readfile("1") as zfe:
                self.assertEqual(zfe.read(), b"more contents") 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:20,代碼來源:test_zipstream.py

示例11: test_unsupportedCompression

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def test_unsupportedCompression(self):
        """
        A zipfile which describes an unsupported compression mechanism should
        raise BadZipfile.
        """
        fn = self.mktemp()
        with zipfile.ZipFile(fn, "w") as zf:
            zi = zipfile.ZipInfo("0")
            zf.writestr(zi, "some data")
            # Mangle its compression type in the central directory; can't do
            # this before the writestr call or zipfile will (correctly) tell us
            # not to pass bad compression types :)
            zi.compress_type = 1234

        with zipstream.ChunkingZipFile(fn) as czf:
            self.assertRaises(zipfile.BadZipfile, czf.readfile, "0") 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:18,代碼來源:test_zipstream.py

示例12: _ParseRelationshipsXMLFile

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def _ParseRelationshipsXMLFile(self, xml_data):
    """Parses the relationships XML file (_rels/.rels).

    Args:
      xml_data (bytes): data of a _rels/.rels XML file.

    Returns:
      list[str]: property file paths. The path is relative to the root of
          the ZIP file.

    Raises:
      zipfile.BadZipfile: if the relationship XML file cannot be read.
    """
    xml_root = ElementTree.fromstring(xml_data)

    property_files = []
    for xml_element in xml_root.iter():
      type_attribute = xml_element.get('Type')
      if 'properties' in repr(type_attribute):
        target_attribute = xml_element.get('Target')
        property_files.append(target_attribute)

    return property_files 
開發者ID:log2timeline,項目名稱:plaso,代碼行數:25,代碼來源:oxml.py

示例13: read_sheets

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def read_sheets(self):
        try:
            self.workbook = openpyxl.load_workbook(self.input_name, data_only=True)
        except BadZipFile as e:  # noqa
            # TODO when we have python3 only add 'from e' to show exception chain
            raise BadXLSXZipFile(
                "The supplied file has extension .xlsx but isn't an XLSX file."
            )

        self.sheet_names_map = OrderedDict(
            (sheet_name, sheet_name) for sheet_name in self.workbook.sheetnames
        )
        if self.include_sheets:
            for sheet in list(self.sheet_names_map):
                if sheet not in self.include_sheets:
                    self.sheet_names_map.pop(sheet)
        for sheet in self.exclude_sheets or []:
            self.sheet_names_map.pop(sheet, None)

        sheet_names = list(sheet for sheet in self.sheet_names_map.keys())
        self.sub_sheet_names = sheet_names
        self.configure_sheets() 
開發者ID:OpenDataServices,項目名稱:flatten-tool,代碼行數:24,代碼來源:input.py

示例14: archive_context

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def archive_context(filename):
    """
    Unzip filename to a temporary directory, set to the cwd.

    The unzipped target is cleaned up after.
    """
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        try:
            with ContextualZipFile(filename) as archive:
                archive.extractall()
        except zipfile.BadZipfile as err:
            if not err.args:
                err.args = ('', )
            err.args = err.args + (
                MEANINGFUL_INVALID_ZIP_ERR_MSG.format(filename),
            )
            raise

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
開發者ID:aimuch,項目名稱:iAI,代碼行數:33,代碼來源:ez_setup.py

示例15: extract_xml_strings

# 需要導入模塊: import zipfile [as 別名]
# 或者: from zipfile import BadZipfile [as 別名]
def extract_xml_strings(filename):
    """
    Given a string [filename], opens the file and returns a generator
    that yields tuples. A tuple is of format (year, xmldoc string). A tuple
    is returned for every valid XML doc in [filename]
    """
    # search for terminating XML tag
    endtag_regex = re.compile('^<!DOCTYPE (.*) SYSTEM')
    endtag = ''
    import zipfile
    import os
    try:
        z = zipfile.ZipFile(filename, 'r')
    except zipfile.BadZipfile as e:
        print e
        return
    xmlfilename = os.path.basename(filename)[:-4] + ".xml"
    with z.open(xmlfilename, 'r') as f:
        doc = ''  # (re)initialize current XML doc to empty string
        for line in f:
            doc += line
            endtag = endtag_regex.findall(line) if not endtag else endtag
            if not endtag:
                continue
            terminate = re.compile('^</{0}>'.format(endtag[0]))
            if terminate.findall(line):
                yield doc
                endtag = ''
                doc = ''
    z.close()

# This follows google's rules for conversion of XML to JSON 
開發者ID:dataiku,項目名稱:dataiku-contrib,代碼行數:34,代碼來源:connector.py


注:本文中的zipfile.BadZipfile方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。