本文整理汇总了Python中zipfile.is_zipfile函数的典型用法代码示例。如果您正苦于以下问题:Python is_zipfile函数的具体用法?Python is_zipfile怎么用?Python is_zipfile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_zipfile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: download_update
def download_update(self):
if self.update_available:
if os.path.exists(paths.UPDATE_FILE_PATH) and zipfile.is_zipfile(paths.UPDATE_FILE_PATH):
self.logger.info('Update package already downloaded')
else:
self.logger.info('Downloading update package...')
try:
urllib.urlretrieve(self.update_download_url, paths.UPDATE_FILE_PATH)
except Exception as e:
error_message = 'Update download failed: error while downloading from %s\nDetails: %s' %\
( self.update_download_url, str(e) )
self.logger.warning(error_message)
return error_message
else:
if zipfile.is_zipfile(paths.UPDATE_FILE_PATH):
self.logger.info('...update successfully downloaded!')
self.update_available = False
log.send_logs()
else:
error_message = 'Error: corrupted update package.'
self.logger.warning(error_message)
try:
os.remove(paths.UPDATE_FILE_PATH)
except:
self.logger.warning("Unable to remove corrupted update package.")
else:
self.logger.warning("Corrupted update package removed.")
return error_message
示例2: getZipFilePath
def getZipFilePath(filePath, stopPath=""):
"""
Detect if part or all of the given path points to a ZIP file
@param filePath: string
The full path to the resource
@return: tuple(string, string)
Returns a tuple with the following content:
1. path to the ZIP file in OS format (using OS path separator)
2. ZIP internal path to the requested file in ZIP format
"""
assert isinstance(filePath, str), "Invalid file path %s" % filePath
assert isinstance(stopPath, str), "Invalid stop path %s" % stopPath
# make sure the file path is normalized and uses the OS separator
filePath = normOSPath(filePath, True)
if is_zipfile(filePath):
return filePath, ""
parentPath = filePath
stopPathLen = len(stopPath)
while len(parentPath) > stopPathLen:
if is_zipfile(parentPath):
return parentPath, normZipPath(filePath[len(parentPath) :])
nextSubPath = dirname(parentPath)
if nextSubPath == parentPath:
break
parentPath = nextSubPath
raise IOError("Invalid ZIP path %s" % filePath)
示例3: __init__
def __init__(self, filename, UserData=None, new=None):
if filename:
self.filename = os.path.abspath(filename)
else:
self.filename = None
# initialize isZip, but leave it until first save to decide the file type
self.isZip = True
if new:
self.tempfile = "%s/%i.exp~" % (UserData.GetTempDir()\
,random.randint(0, 1000))
self.NewScreen()
return
elif zipfile.is_zipfile(filename) and UserData:
# setup temp file
self.tempfile = "%s/%s%i.exp~" % (UserData.GetTempDir(),os.path.split(filename)[1]\
,random.randint(0, 1000))
self.StartTemp()
self.ReadZip()
elif zipfile.is_zipfile(filename):
self.tempfile = "tempfile.zip"
self.StartTemp()
self.ReadZip()
self.isZip = False
else:
self.ReadFile()
示例4: walkzip
def walkzip(self, path):
"""Walks a path independent of whether it includes a zipfile or not"""
if os.path.exists(path) and os.path.isdir(path):
for dirpath, _dirnames, filenames in os.walk(path):
for filename in filenames:
# Run through files as we always used to
yield os.path.join(dirpath[len(path) + len(os.path.sep):], filename)
else:
index = -1
zippath = None
while path.find(os.path.sep, index + 1) > -1:
index = path.find(os.path.sep, index + 1)
if zipfile.is_zipfile(path[:index]):
zippath = path[:index]
break
else:
if zipfile.is_zipfile(path):
zippath = path
# Now yield the files
if zippath:
zipf = zipfile.ZipFile(zippath)
prefix = path[len(zippath):].strip(os.path.sep)
# If there's a prefix, ensure it ends in a slash
if len(prefix):
prefix += os.path.sep
for fn in zipf.namelist():
# Zipfiles seem to always list contents using / as their separator
fn = fn.replace('/', os.path.sep)
if fn.startswith(prefix) and not fn.endswith(os.path.sep):
# We're a file in the zipfile
yield fn[len(prefix):]
示例5: _get_layer_values
def _get_layer_values(layer, upload_session, expand=0):
layer_values = []
if upload_session:
absolute_base_file = upload_session.base_file[0].base_file
tempdir = upload_session.tempdir
if not os.path.isfile(absolute_base_file):
tmp_files = [f for f in os.listdir(tempdir) if os.path.isfile(os.path.join(tempdir, f))]
for f in tmp_files:
if zipfile.is_zipfile(os.path.join(tempdir, f)):
absolute_base_file = unzip_file(os.path.join(tempdir, f), '.shp', tempdir=tempdir)
absolute_base_file = os.path.join(tempdir,
absolute_base_file)
elif zipfile.is_zipfile(absolute_base_file):
absolute_base_file = unzip_file(upload_session.base_file[0].base_file,
'.shp', tempdir=tempdir)
absolute_base_file = os.path.join(tempdir,
absolute_base_file)
inDataSource = ogr.Open(absolute_base_file)
lyr = inDataSource.GetLayer(str(layer.name))
limit = 100
for feat in islice(lyr, 0, limit):
feat_values = json_loads_byteified(feat.ExportToJson()).get('properties')
for k in feat_values.keys():
type_code = feat.GetFieldDefnRef(k).GetType()
binding = feat.GetFieldDefnRef(k).GetFieldTypeName(type_code)
feat_value = feat_values[k] if str(feat_values[k]) != 'None' else 0
if expand > 0:
ff = {'value': feat_value, 'binding': binding}
feat_values[k] = ff
else:
feat_values[k] = feat_value
layer_values.append(feat_values)
return layer_values
示例6: main
def main(arg):
if os.path.isdir(arg):
rootdir = arg
for parent, dirnames, filenames in os.walk(rootdir):
for filename in filenames:
filePath = os.path.join(parent, filename)
print(filePath)
if zipfile.is_zipfile(filePath):
try:
with zipfile.ZipFile(filePath, mode="r") as z:
print_infos(z)
if len(files_list) > 0:
print_sub_zips(z)
files_list.clear()
except zipfile.BadZipFile as z:
print(filePath, e)
elif os.path.isfile(arg):
if zipfile.is_zipfile(arg):
try:
with zipfile.ZipFile(arg, mode="r") as z:
print_infos(z)
if len(files_list) > 0:
print_sub_zips(z)
files_list.clear()
except zipfile.BadZipFile as z:
print(filePath, e)
示例7: test_make_zipfile
def test_make_zipfile(self):
# creating something to zip
root_dir, base_dir = self._create_files()
tmpdir2 = self.mkdtemp()
# force shutil to create the directory
os.rmdir(tmpdir2)
# working with relative paths
work_dir = os.path.dirname(tmpdir2)
rel_base_name = os.path.join(os.path.basename(tmpdir2), 'archive')
with support.change_cwd(work_dir):
base_name = os.path.abspath(rel_base_name)
res = make_archive(rel_base_name, 'zip', root_dir)
self.assertEqual(res, base_name + '.zip')
self.assertTrue(os.path.isfile(res))
self.assertTrue(zipfile.is_zipfile(res))
with zipfile.ZipFile(res) as zf:
self.assertEqual(sorted(zf.namelist()),
['dist/', 'dist/file1', 'dist/file2',
'dist/sub/', 'dist/sub/file3', 'dist/sub2/',
'outer'])
with support.change_cwd(work_dir):
base_name = os.path.abspath(rel_base_name)
res = make_archive(rel_base_name, 'zip', root_dir, base_dir)
self.assertEqual(res, base_name + '.zip')
self.assertTrue(os.path.isfile(res))
self.assertTrue(zipfile.is_zipfile(res))
with zipfile.ZipFile(res) as zf:
self.assertEqual(sorted(zf.namelist()),
['dist/', 'dist/file1', 'dist/file2',
'dist/sub/', 'dist/sub/file3', 'dist/sub2/'])
示例8: addpoints_to_scan
def addpoints_to_scan(scanid,req_format,parnames,points):
point_requests = []
basic_requests = []
for i,p in enumerate(points):
coordinates = p['coordinates']
data = p['data']
if os.path.isdir(data):
_,archive = tempfile.mkstemp()
with zipfile.ZipFile(archive,'w') as archivefile:
for d,_,fl in os.walk(data):
for f in fl:
archivefile.write(os.path.join(d,f), arcname = os.path.relpath(os.path.join(d,f),data))
elif zipfile.is_zipfile(data):
archive = data
else:
print data
print os.path.isdir(data)
print zipfile.is_zipfile(data)
raise click.ClickException('point data needs to be zipfiles or directory')
pointdict = dict(zip(parnames,coordinates))
pr = recastapi.request.write.point_request_with_coords(scanid,pointdict)
point_requests += [{'point':pointdict,'id':pr['id']}]
br = recastapi.request.write.basic_request_with_archive(pr['id'],archive,req_format)
basic_requests += [{'point':pointdict,'id':br['id'], 'point_request': pr['id']}]
click.secho('uploaded {}/{} requests'.format(i+1,len(points)))
return point_requests, basic_requests
示例9: __init__
def __init__(self, original, modified):
self.TEXTCHARS = ''.join(map(chr, [7,8,9,10,12,13,27] + range(0x20, 0x100)))
self.ALLBYTES = ''.join(map(chr, range(256)))
self.changelist = [
(0, 'No Change'),
(1, 'File Removed'),
(2, 'File Added'),
(3, 'Binary File Change'),
(4, 'Text File Change (With Diff)'),
(5, 'Text File Change (Without Diff)'),
]
if os.path.exists(original) and os.path.exists(modified):
if zipfile.is_zipfile(original) and zipfile.is_zipfile(modified):
self.original = zipfile.ZipFile(original)
self.modified = zipfile.ZipFile(modified)
else:
raise EpubDiffError("One or more files are not Epub/Zip files")
else:
raise EpubDiffError("One or more files do not exist")
self.doclist = [(self.original, 0), (self.modified, 1)]
self.manifest = {}
self.difflog = []
示例10: read_class_path
def read_class_path(class_path):
'''Cache content of all jars.
Begin with rt.jar
'''
# folders for lookup for class files
lookup_paths = []
# content of all jars (name->path to jar)
jars = {}
# content of rt.jar
rt = {}
# first check local rt.jar
local_path = os.path.dirname(os.path.realpath(__file__))
RT_JAR = os.path.join(local_path, "../rt/rt.jar")
if not os.path.isfile(RT_JAR):
JAVA_HOME = os.environ.get('JAVA_HOME')
if JAVA_HOME is None:
raise Exception("JAVA_HOME is not set")
if not os.path.isdir(JAVA_HOME):
raise Exception("JAVA_HOME must be a folder: %s" % JAVA_HOME)
RT_JAR = os.path.join(JAVA_HOME, "lib/rt.jar")
if not os.path.exists(RT_JAR) or os.path.isdir(RT_JAR):
RT_JAR = os.path.join(JAVA_HOME, "jre/lib/rt.jar")
if not os.path.exists(RT_JAR) or os.path.isdir(RT_JAR):
raise Exception("rt.jar not found")
if not zipfile.is_zipfile(RT_JAR):
raise Exception("rt.jar is not a zip: %s" % RT_JAR)
read_from_jar(RT_JAR, rt)
current = os.getcwd()
splitter = None
if ":" in class_path:
splitter = ":"
elif ";" in class_path:
splitter = ";"
elif "," in class_path:
splitter = ","
else:
splitter = ":"
cpaths = class_path.split(splitter)
for p in cpaths:
p = p.strip()
path = os.path.join(current, p)
if not os.path.exists(path):
raise Exception("Wrong class path entry: %s (path not found %s)",
p, path)
if os.path.isdir(path):
lookup_paths.append(path)
else:
if zipfile.is_zipfile(path):
read_from_jar(path, jars)
else:
raise Exception("Class path entry %s is not a jar file" % path)
return (lookup_paths, jars, rt)
示例11: process_log_path
def process_log_path(self, log_path):
"""
Detect if log_path is a zip, then unzip it and return log's location.
:param log_path:
:return: log location - if the log_path is not a zip
unzipped location - if log_path is a zip
list of zipped logs - if log_path contains the zipped logs
"""
if zipfile.is_zipfile(log_path):
dir_path = os.path.dirname(os.path.abspath(log_path))
# extracting zip to current path
# it is required that all logs are zipped in a folder
with zipfile.ZipFile(log_path, 'r') as z:
if any('/' in fis for fis in z.namelist()):
unzip_folder = z.namelist()[0].split('/')[0]
else:
unzip_folder = ''
z.extractall(dir_path)
if unzip_folder:
self.cleanup = True
return os.path.join(dir_path, unzip_folder)
elif any(zipfile.is_zipfile(os.path.join(log_path, z))
for z in os.listdir(log_path)):
zip_list = []
for z in os.listdir(log_path):
zip_file_path = os.path.join(log_path, z)
if zipfile.is_zipfile(zip_file_path):
zip_list.append(self.process_log_path(zip_file_path))
return zip_list
else:
return log_path
示例12: subtitlesDownload
def subtitlesDownload(listOfId):
global pocitadlo
print("Stahuji titulky k filmu s opacnym jazykem...")
for item in listOfId:
pocitadlo = pocitadlo + 1
download = "http://www.opensubtitles.org/cs/subtitleserve/sub/"+item
if not os.path.exists("ENG"):
print("Vytvarim slozku ENG")
os.makedirs("ENG")
urlObjDownload = urllib2.urlopen(download)
outFile = open("ENG/sub"+`pocitadlo`,"wb")
outFile.write(urlObjDownload.read())
if(zipfile.is_zipfile(outFile)):
isZipFile = True
else:
isZipFile = False
outFile.close()
print "Rozbaluji stazene zip file s titulkama..."
pocitadlo = pocitadlo + 1
for i in range(1,pocitadlo):
if(zipfile.is_zipfile("ENG/sub"+`i`)):
zfile = zipfile.ZipFile("ENG/sub"+`i`)
for name in zfile.namelist():
if(re.search(".*\.nfo$",name)):
continue
(dirname, filename) = os.path.split(name)
zfile.extract(name, "ENG")
else:
try:
os.rename("ENG/sub"+`i`, "ENG/sub"+`i`+".srt")
except:
pass
示例13: Create
def Create(self, add_files = []):
dir_name, base_name = os.path.split(self.fn)
name, ext = os.path.splitext(base_name)
### output zip file
zout = zipfile.ZipFile(self.fn, "w")
### for all files wich could be added
for fn in filter(lambda f: os.path.exists(f) or zipfile.is_zipfile(os.path.dirname(f)), add_files):
fn_dir_name, fn_base_name = os.path.split(fn)
fn_name, fn_ext = os.path.splitext(fn_base_name)
### if adding file is compressed, we decompress and add it
if zipfile.is_zipfile(fn_dir_name):
zin = zipfile.ZipFile(fn_dir_name, 'r')
buffer = zin.read(fn_base_name)
### if not .dat file and the name of file is not the same with the zip file
#if fn_ext == '.py':
#zout.writestr("%s%s"%(name,fn_ext), buffer)
#else:
zout.writestr(fn_base_name, buffer)
zin.close()
else:
zout.write(fn, fn_base_name)
zout.close()
示例14: open_possibly_compressed_file
def open_possibly_compressed_file(filename):
if not os.path.exists(filename):
raise IOError("cannot find file `" + filename + "'")
if sys.version_info[:2] < (2, 6) and zipfile.is_zipfile(filename):
raise IOError("cannot unpack a ZIP file with Python %s" %
'.'.join(map(str, sys.version_info)))
try:
is_zipfile = zipfile.is_zipfile(filename)
except:
is_zipfile = False
if is_zipfile:
zf1 = zipfile.ZipFile(filename, "r")
if len(zf1.namelist()) != 1:
raise IOError("cannot compare with a zip file that contains "
"multiple files: `" + filename + "'")
if sys.version_info < (3, 0):
return zf1.open(zf1.namelist()[0], 'r')
else:
return io.TextIOWrapper(
zf1.open(zf1.namelist()[0], 'r'), encoding='utf-8', newline='')
elif filename.endswith('.gz'):
if sys.version_info < (3, 0):
return gzip.open(filename, "r")
elif sys.version_info[:2] == (3, 2):
return io.TextIOWrapper(
MyGzipFile(filename), encoding='utf-8', newline='')
else:
return io.TextIOWrapper(
gzip.open(filename, 'r'), encoding='utf-8', newline='')
else:
return open(filename, "r")
示例15: list
def list(self, options, args):
if args:
raise InstallationError("You cannot give an argument with --list")
for path in sorted(self.paths()):
if not os.path.exists(path):
continue
basename = os.path.basename(path.rstrip(os.path.sep))
if os.path.isfile(path) and zipfile.is_zipfile(path):
if os.path.dirname(path) not in self.paths():
logger.notify("Zipped egg: %s" % display_path(path))
continue
if (
basename != "site-packages"
and basename != "dist-packages"
and not path.replace("\\", "/").endswith("lib/python")
):
continue
logger.notify("In %s:" % display_path(path))
logger.indent += 2
zipped = []
unzipped = []
try:
for filename in sorted(os.listdir(path)):
ext = os.path.splitext(filename)[1].lower()
if ext in (".pth", ".egg-info", ".egg-link"):
continue
if ext == ".py":
logger.info("Not displaying %s: not a package" % display_path(filename))
continue
full = os.path.join(path, filename)
if os.path.isdir(full):
unzipped.append((filename, self.count_package(full)))
elif zipfile.is_zipfile(full):
zipped.append(filename)
else:
logger.info("Unknown file: %s" % display_path(filename))
if zipped:
logger.notify("Zipped packages:")
logger.indent += 2
try:
for filename in zipped:
logger.notify(filename)
finally:
logger.indent -= 2
else:
logger.notify("No zipped packages.")
if unzipped:
if options.sort_files:
unzipped.sort(key=lambda x: -x[1])
logger.notify("Unzipped packages:")
logger.indent += 2
try:
for filename, count in unzipped:
logger.notify("%s (%i files)" % (filename, count))
finally:
logger.indent -= 2
else:
logger.notify("No unzipped packages.")
finally:
logger.indent -= 2