Python zipfile.BadZipFile() Examples
The following are 30
code examples of zipfile.BadZipFile().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
zipfile
, or try the search function
.
Example #1
Source File: test_zipfile.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def test_empty_zipfile(self): # Check that creating a file in 'w' or 'a' mode and closing without # adding any files to the archives creates a valid empty ZIP file zipf = zipfile.ZipFile(TESTFN, mode="w") zipf.close() try: zipf = zipfile.ZipFile(TESTFN, mode="r") except zipfile.BadZipFile: self.fail("Unable to create empty ZIP file in 'w' mode") zipf = zipfile.ZipFile(TESTFN, mode="a") zipf.close() try: zipf = zipfile.ZipFile(TESTFN, mode="r") except: self.fail("Unable to create empty ZIP file in 'a' mode")
Example #2
Source File: ThreeMFWorkspaceReader.py From Cura with GNU Lesser General Public License v3.0 | 6 votes |
def _loadMetadata(file_name: str) -> Dict[str, Dict[str, Any]]: result = dict() # type: Dict[str, Dict[str, Any]] try: archive = zipfile.ZipFile(file_name, "r") except zipfile.BadZipFile: Logger.logException("w", "Unable to retrieve metadata from {fname}: 3MF archive is corrupt.".format(fname = file_name)) return result metadata_files = [name for name in archive.namelist() if name.endswith("plugin_metadata.json")] for metadata_file in metadata_files: try: plugin_id = metadata_file.split("/")[0] result[plugin_id] = json.loads(archive.open("%s/plugin_metadata.json" % plugin_id).read().decode("utf-8")) except Exception: Logger.logException("w", "Unable to retrieve metadata for %s", metadata_file) return result
Example #3
Source File: sourceLoader.py From Thespian with MIT License | 6 votes |
def _getFromZipFile(self, getter): plainsrc = self.decryptor(self.enczfsrc) try: z = ZipFile(BytesIO(plainsrc)) except BadZipFile as ex: logging.error('Invalid zip contents (%s) for source hash %s: %s', str(plainsrc) if not plainsrc or len(plainsrc) < 100 else str(plainsrc[:97]) + '...', self.srcHash, ex) raise try: return getter(z) finally: # Try to be hygenic. This is an interpreted language, but do what we can... z.close() del z # Strings in Python are typically immutable; attempts to # modify the string will likely just make more copies, so just # tell the interpreter to get rid of the main copy asap. del plainsrc
Example #4
Source File: common.py From sciwing with MIT License | 6 votes |
def extract_zip(filename: str, destination_dir: str): """ Extracts a zipped file Parameters ---------- filename : str The zipped filename destination_dir : str The directory where the zipped will be placed """ msg_printer = Printer() try: with msg_printer.loading(f"Unzipping file {filename} to {destination_dir}"): stdout.flush() with zipfile.ZipFile(filename, "r") as z: z.extractall(destination_dir) msg_printer.good(f"Finished extraction {filename} to {destination_dir}") except zipfile.BadZipFile: msg_printer.fail(f"Couldnot extract {filename} to {destination_dir}")
Example #5
Source File: zip.py From maubot with GNU Affero General Public License v3.0 | 6 votes |
def _read_meta(source) -> Tuple[ZipFile, PluginMeta]: try: file = ZipFile(source) data = file.read("maubot.yaml") except FileNotFoundError as e: raise MaubotZipMetaError("Maubot plugin not found") from e except BadZipFile as e: raise MaubotZipMetaError("File is not a maubot plugin") from e except KeyError as e: raise MaubotZipMetaError("File does not contain a maubot plugin definition") from e try: meta_dict = yaml.load(data) except (YAMLError, KeyError, IndexError, ValueError) as e: raise MaubotZipMetaError("Maubot plugin definition file is not valid YAML") from e try: meta = PluginMeta.deserialize(meta_dict) except SerializerError as e: raise MaubotZipMetaError("Maubot plugin definition in file is invalid") from e return file, meta
Example #6
Source File: template.py From SalesforceXyTools with Apache License 2.0 | 6 votes |
def extract_template(package_path): print("package_path" + package_path) root_path = os.path.join(tempfile.gettempdir(), "salesforcexytools") try: zfile = zipfile.ZipFile(package_path, 'r') for filename in zfile.namelist(): if filename.endswith('/'): continue if filename.endswith('.py'): continue if filename.startswith("templates/"): f = os.path.join(root_path, filename) if not os.path.exists(os.path.dirname(f)): os.makedirs(os.path.dirname(f)) with open(f, "wb") as fp: fp.write(zfile.read(filename)) except zipfile.BadZipFile as ex: print(str(ex)) return
Example #7
Source File: __init__.py From blender-plugin with Apache License 2.0 | 6 votes |
def unzip_archive(archive_path): if os.path.exists(archive_path): set_import_status('Unzipping model') import zipfile try: zip_ref = zipfile.ZipFile(archive_path, 'r') extract_dir = os.path.dirname(archive_path) zip_ref.extractall(extract_dir) zip_ref.close() except zipfile.BadZipFile: print('Error when dezipping file') os.remove(archive_path) print('Invaild zip. Try again') set_import_status('') return None, None gltf_file = os.path.join(extract_dir, 'scene.gltf') return gltf_file, archive_path else: print('ERROR: archive doesn\'t exist')
Example #8
Source File: test_zipfile.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
def test_read_with_bad_crc(self): """Tests that files with bad CRCs raise a BadZipFile exception when read.""" zipdata = self.zip_with_bad_crc # 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
Example #9
Source File: common.py From fdroidserver with GNU Affero General Public License v3.0 | 6 votes |
def get_apk_id(apkfile): """Extract identification information from APK. Androguard is preferred since it is more reliable and a lot faster. Occasionally, when androguard can't get the info from the APK, aapt still can. So aapt is also used as the final fallback method. :param apkfile: path to an APK file. :returns: triplet (appid, version code, version name) """ if use_androguard(): try: return get_apk_id_androguard(apkfile) except zipfile.BadZipFile as e: logging.error(apkfile + ': ' + str(e)) if 'aapt' in config: return get_apk_id_aapt(apkfile) else: return get_apk_id_aapt(apkfile)
Example #10
Source File: test_zipfile.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
def test_read_with_bad_crc(self): """Tests that files with bad CRCs raise a BadZipFile exception when read.""" zipdata = self.zip_with_bad_crc # 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
Example #11
Source File: test_zipfile.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 6 votes |
def test_empty_zipfile(self): # Check that creating a file in 'w' or 'a' mode and closing without # adding any files to the archives creates a valid empty ZIP file zipf = zipfile.ZipFile(TESTFN, mode="w") zipf.close() try: zipf = zipfile.ZipFile(TESTFN, mode="r") except zipfile.BadZipFile: self.fail("Unable to create empty ZIP file in 'w' mode") zipf = zipfile.ZipFile(TESTFN, mode="a") zipf.close() try: zipf = zipfile.ZipFile(TESTFN, mode="r") except: self.fail("Unable to create empty ZIP file in 'a' mode")
Example #12
Source File: lib.py From linux-show-player with GNU General Public License v3.0 | 6 votes |
def import_has_conflicts(archive): """Verify if the `archive` files conflicts with the user presets. :param archive: path of the archive to analyze :type archive: str :rtype: bool """ try: with ZipFile(archive) as archive: for member in archive.namelist(): if preset_exists(member): return True except(OSError, BadZipFile) as e: raise PresetImportError(str(e)) return False
Example #13
Source File: lib.py From linux-show-player with GNU General Public License v3.0 | 6 votes |
def import_conflicts(archive): """Return a list of conflicts between `archive` files and user presets. :param archive: path of the archive to analyze :type archive: str """ conflicts = [] try: with ZipFile(archive) as archive: for member in archive.namelist(): if preset_exists(member): conflicts.append(member) except(OSError, BadZipFile) as e: raise PresetImportError(str(e)) return conflicts
Example #14
Source File: PluginRegistry.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
def _getPluginIdFromFile(self, filename: str) -> Optional[str]: plugin_id = None try: with zipfile.ZipFile(filename, "r") as zip_ref: for file_info in zip_ref.infolist(): if file_info.filename.endswith("/"): plugin_id = file_info.filename.strip("/") break except zipfile.BadZipFile: Logger.logException("e", "Failed to load plug-in file. The zip archive seems to be corrupt.") return None # Signals that loading this failed. except FileNotFoundError: Logger.logException("e", "Failed to load plug-in file as we were unable to find it.") return None # Signals that loading this failed. return plugin_id # Returns a list of all possible plugin ids in the plugin locations:
Example #15
Source File: PackageManager.py From Uranium with GNU Lesser General Public License v3.0 | 6 votes |
def getPackageLicense(self, filename: str) -> Optional[str]: license_string = None def is_license(zipinfo: zipfile.ZipInfo) -> bool: return os.path.basename(zipinfo.filename).startswith("LICENSE") try: with zipfile.ZipFile(filename) as archive: # Go through all the files and use the first successful read as the result license_files = sorted(filter(is_license, archive.infolist()), key = lambda x: len(x.filename)) # Find the one with the shortest path. for file_info in license_files: Logger.log("d", "Found potential license file '{filename}'".format(filename = file_info.filename)) try: with archive.open(file_info.filename, "r") as f: data = f.read() license_string = data.decode("utf-8") break except: Logger.logException("e", "Failed to load potential license file '%s' as text file.", file_info.filename) license_string = None except zipfile.BadZipFile as e: Logger.error("Package is corrupt: {err}".format(err = str(e))) license_string = None except UnicodeDecodeError: Logger.error("Package filenames are not UTF-8 encoded! Encoding unknown.") license_string = None return license_string
Example #16
Source File: input.py From flatten-tool with MIT License | 6 votes |
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()
Example #17
Source File: test_zipfile.py From ironpython3 with Apache License 2.0 | 6 votes |
def test_empty_zipfile(self): # Check that creating a file in 'w' or 'a' mode and closing without # adding any files to the archives creates a valid empty ZIP file zipf = zipfile.ZipFile(TESTFN, mode="w") zipf.close() try: zipf = zipfile.ZipFile(TESTFN, mode="r") except zipfile.BadZipFile: self.fail("Unable to create empty ZIP file in 'w' mode") zipf = zipfile.ZipFile(TESTFN, mode="a") zipf.close() try: zipf = zipfile.ZipFile(TESTFN, mode="r") except: self.fail("Unable to create empty ZIP file in 'a' mode")
Example #18
Source File: test_zipfile.py From ironpython3 with Apache License 2.0 | 6 votes |
def test_read_with_bad_crc(self): """Tests that files with bad CRCs raise a BadZipFile exception when read.""" zipdata = self.zip_with_bad_crc # 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
Example #19
Source File: main.py From binaryalert with Apache License 2.0 | 6 votes |
def _process_md5(md5: str) -> bool: """Download the given file from CarbonBlack and upload to S3, returning True if successful.""" try: binary = CARBON_BLACK.select(Binary, md5) _upload_to_s3(binary) return True except zipfile.BadZipFile: LOGGER.exception('[BadZipFile] Error downloading %s', md5) LOGGER.info('This md5 is invalid and will not retried') return False except (BotoCoreError, ServerError): LOGGER.exception('Error downloading %s', md5) LOGGER.error( 'A temporary error was encountered during downloading. This md5 will be ' 'retried at a later time.' ) raise except ObjectNotFoundError: LOGGER.exception('Error downloading %s', md5) LOGGER.info( 'This may be caused due to a race condition where the requested binary is not yet ' 'available for download from the server. This binary will be retried at a later time.' ) raise
Example #20
Source File: container_test.py From surround with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_open_corrupt_container(self): with self.assertRaises(FileNotFoundError): DataContainer('test-container.data.zip') with open("test-container.data.zip", "w+") as f: f.write("INVALID_ZIP_DATA") with self.assertRaises(zipfile.BadZipFile): DataContainer('test-container.data.zip') os.unlink('test-container.data.zip') with zipfile.ZipFile('test-container.data.zip', 'w') as f: f.writestr('bad.txt', 'BAD') with self.assertRaises(MetadataNotFoundError): DataContainer('test-container.data.zip') os.unlink('test-container.data.zip')
Example #21
Source File: test_io.py From scprep with GNU General Public License v3.0 | 5 votes |
def test_10X_zip_url_not_a_zip(): utils.assert_raises_message( zipfile.BadZipFile, "File is not a zip file", scprep.io.load_10X_zip, "https://github.com/KrishnaswamyLab/scprep/raw/master/data/test_data/test_10X", )
Example #22
Source File: test_zipfile.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_damaged_zipfile(self): """Check that zipfiles with missing bytes at the end raise BadZipFile.""" # - Create a valid zip file fp = io.BytesIO() with zipfile.ZipFile(fp, mode="w") as zipf: zipf.writestr("foo.txt", b"O, for a Muse of Fire!") zipfiledata = fp.getvalue() # - Now create copies of it missing the last N bytes and make sure # a BadZipFile exception is raised when we try to open it for N in range(len(zipfiledata)): fp = io.BytesIO(zipfiledata[:N]) self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp)
Example #23
Source File: helpers.py From OpenSarToolkit with MIT License | 5 votes |
def check_zipfile(filename): try: zip_archive = zipfile.ZipFile(filename) except zipfile.BadZipFile as er: print('Error: {}'.format(er)) return 1 try: zip_test = zip_archive.testzip() except: print('Error') return 1 else: return zip_test
Example #24
Source File: taskcluster.py From code-coverage with Mozilla Public License 2.0 | 5 votes |
def download_artifact(artifact_path, task_id, artifact_name): if os.path.exists(artifact_path): return artifact_path # Build artifact public url # Use un-authenticated Taskcluster client to avoid taskcluster-proxy rewrite issue # https://github.com/taskcluster/taskcluster-proxy/issues/44 queue = taskcluster.Queue({"rootUrl": "https://firefox-ci-tc.services.mozilla.com"}) url = queue.buildUrl("getLatestArtifact", task_id, artifact_name) logger.debug("Downloading artifact", url=url) @tenacity.retry( reraise=True, wait=tenacity.wait_exponential(multiplier=1, min=16, max=64), stop=tenacity.stop_after_attempt(5), ) def perform_download(): r = requests.get(url, stream=True) r.raise_for_status() with open(artifact_path, "wb") as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) if artifact_path.endswith(".zip") and not is_zipfile(artifact_path): raise BadZipFile("File is not a zip file") perform_download()
Example #25
Source File: uploads.py From notifications-admin with MIT License | 5 votes |
def upload_contact_list(service_id): form = CsvUploadForm() if form.validate_on_submit(): try: upload_id = ContactList.upload( current_service.id, Spreadsheet.from_file_form(form).as_dict, ) return redirect(url_for( '.check_contact_list', service_id=service_id, upload_id=upload_id, original_file_name=form.file.data.filename, )) except (UnicodeDecodeError, BadZipFile, XLRDError): flash('Could not read {}. Try using a different file format.'.format( form.file.data.filename )) except (XLDateError): flash(( '{} contains numbers or dates that Notify cannot understand. ' 'Try formatting all columns as ‘text’ or export your file as CSV.' ).format( form.file.data.filename )) return render_template( 'views/uploads/contact-list/upload.html', form=form, )
Example #26
Source File: sourceLoader.py From Thespian with MIT License | 5 votes |
def _loadModuleFromVerifiedHashSource(hashFinder, modName, modClass): hRoot = hashFinder.hashRoot() pkg = importlib.import_module(hRoot) #impModName = modName if modName.startswith(hRoot + '.') else (hRoot + '.' + modName) impModName = modName if modName.startswith(hRoot) else (hRoot + modName) try: m = importlib.import_module(impModName, hRoot) except (BadZipFile, SyntaxError) as ex: raise ImportError('Source hash %s: %s'%(hRoot, str(ex))) return getattr(m, modClass)
Example #27
Source File: data_to_db.py From vcf-to-23andme with MIT License | 5 votes |
def open_file(file_name): data_file = gzip.open(file_name, "rt", encoding="utf8") try: data_file.read(1); except OSError: data_file.close() else: data_file.seek(0); return data_file try: archive = zipfile.ZipFile(file_name) except zipfile.BadZipFile: pass else: for object_name in archive.namelist(): if not object_name.endswith("/"): break else: raise Exception("ZIP Archive has no readable file") data_file = io.TextIOWrapper(archive.open(object_name), encoding="utf8") archive.close() return data_file return open(file_name, "r", encoding="utf8")
Example #28
Source File: importmodule.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def validate_zipfile(module_zipfile: ModuleZipfile) -> None: """ Ensure `path` points to a valid ModuleZipfile. Raise `WorkbenchModuleImportError` with an English-language description of the flaw otherwise. (This can help module authors fix their mistakes.) """ try: module_zipfile.get_spec() # raise KeyError, ValueError, BadZipFile # raise KeyError, UnicodeDecodeError, SyntaxError, BadZipFile compiled_module = module_zipfile.compile_code_without_executing() cjwstate.modules.kernel.validate(compiled_module) # raise ModuleError module_zipfile.get_optional_html() # raise UnicodeError, BadZipFile module_zipfile.get_optional_js_module() # raise UnicodeError, BadZipFile except zipfile.BadZipFile as err: raise WorkbenchModuleImportError("Bad zipfile: %s" % str(err)) from err except ValueError as err: raise WorkbenchModuleImportError( "Module .yaml is invalid: %s" % str(err) ) from err except KeyError as err: raise WorkbenchModuleImportError( "Zipfile is missing a required file: %s" % str(err) ) from err except SyntaxError as err: raise WorkbenchModuleImportError( "Module Python code has a syntax error: %s" % str(err) ) from err except UnicodeError as err: raise WorkbenchModuleImportError( "Module Python, HTML or JS code is invalid UTF-8: %s" % str(err) ) from err except ModuleError as err: raise WorkbenchModuleImportError( "Module Python code failed to run: %s" % str(err) ) from err
Example #29
Source File: test_zipfile.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_close_on_exception(self): """Check that the zipfile is closed if an exception is raised in the 'with' block.""" with zipfile.ZipFile(TESTFN2, "w") as zipfp: for fpath, fdata in SMALL_TEST_DATA: zipfp.writestr(fpath, fdata) try: with zipfile.ZipFile(TESTFN2, "r") as zipfp2: raise zipfile.BadZipFile() except zipfile.BadZipFile: self.assertIsNone(zipfp2.fp, 'zipfp is not closed')
Example #30
Source File: zip_cracker.py From arissploit with GNU General Public License v3.0 | 5 votes |
def run(self): if variables["file"][0] == "": printError("No zip file specified!") return ModuleError("No zip file specified!") file = variables["file"][0] if os.path.exists(file): if os.path.isdir(file): printError("Error: "+file+": is a directory!") return ModuleError("Error: "+file+": is a directory!") else: zipf = zipfile.ZipFile(file) else: printError("Input file: "+file+": does not exist!") return ModuleError("Input file: "+file+": does not exist!") for word in self.words: if self.pwdh.pwd != None: return elif self.pwdh.error != None: return elif self.pwdh.kill == True: return try: word = word.decode("utf-8").replace("\n", "") if word[0] == "#": continue #animline("trying password: "+word) zipf.extractall(variables["exto"][0], pwd=word.encode("utf-8")) self.pwdh.pwd = word return except RuntimeError: pass except zipfile.BadZipFile: pass