本文整理汇总了Python中zipfile.is_zipfile函数的典型用法代码示例。如果您正苦于以下问题:Python is_zipfile函数的具体用法?Python is_zipfile怎么用?Python is_zipfile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_zipfile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:SHINOTECH,项目名称:3dprinteros-client,代码行数:28,代码来源:updater.py
示例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)
开发者ID:sourcefabric,项目名称:Ally-Py-Backup,代码行数:29,代码来源:util_zip.py
示例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()
开发者ID:tschalch,项目名称:pyTray,代码行数:27,代码来源:elmtree_backend.py
示例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):]
开发者ID:abrieff,项目名称:Portfolio,代码行数:32,代码来源:registry.py
示例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
开发者ID:atenekom,项目名称:geonode,代码行数:34,代码来源:utils.py
示例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)
开发者ID:jwtgoogle,项目名称:amas,代码行数:26,代码来源:apkinfos.py
示例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/'])
开发者ID:Kelauni22,项目名称:Meeple,代码行数:35,代码来源:test_shutil.py
示例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
开发者ID:recast-hep,项目名称:recast-api,代码行数:29,代码来源:apicli.py
示例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 = []
开发者ID:nicwest,项目名称:epubdiff,代码行数:26,代码来源:epubdiff.py
示例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)
开发者ID:4toblerone,项目名称:pyjvm,代码行数:60,代码来源:class_path.py
示例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
开发者ID:bogdancarpusor,项目名称:lis-test,代码行数:31,代码来源:file_parser.py
示例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
开发者ID:xxMAKMAKxx,项目名称:school-projects,代码行数:34,代码来源:xkacma03.py
示例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()
开发者ID:CelineBateauKessler,项目名称:DEVSimPy,代码行数:25,代码来源:ZipManager.py
示例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")
开发者ID:PyUtilib,项目名称:pyutilib,代码行数:31,代码来源:comparison.py
示例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
开发者ID:saxix,项目名称:pip,代码行数:60,代码来源:zip.py
示例16: GetModule
def GetModule(filename):
""" Give module object from python file path. Warning, the name of python_file must be the same of the classe name.
"""
dir_name = os.path.dirname(filename)
### if python_file is ...../toto.amd/Atomic_Model.py, then the parent dir is zipfile.
if zipfile.is_zipfile(dir_name):
zf = ZipManager.Zip(dir_name)
return zf.GetModule()
elif zipfile.is_zipfile(filename):
zf = ZipManager.Zip(filename)
return zf.GetModule()
### if python file is on the web !
elif filename.startswith(('http','https')):
net = Net(filename)
return net.GetModule()
### pure python file
else:
### add path to sys.path
if dir_name not in sys.path:
sys.path.append(dir_name)
module_name = os.path.basename(filename).split('.py')[0]
# find and load module
try:
f, fn, description = imp.find_module(module_name, [dir_name])
module = imp.load_module(module_name, f, fn, description)
f.close()
return module
except Exception, info:
return sys.exc_info()
开发者ID:AsmaDhanePersonal,项目名称:DEVSimPy,代码行数:35,代码来源:Components.py
示例17: 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
开发者ID:boyshousemedia,项目名称:mediaserver,代码行数:58,代码来源:zip.py
示例18: GetAttr
def GetAttr(self, row, col, kind):
"""
"""
attr = gridlib.GridCellAttr()
val = self.GetValue(row, col)
### format font of attr
if col == 0:
attr.SetReadOnly(True)
attr.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
#attr.SetBackgroundColour("light blue")
elif col == 2:
attr.SetReadOnly(True)
attr.SetFont(wx.Font(10, wx.SWISS, wx.ITALIC, wx.NORMAL))
else:
### load color in cell for pen and fill
if isinstance(val, list):
### if elem in list begin by #. It is color.
for s in filter(lambda a: a.startswith('#'), map(str, val)):
attr.SetBackgroundColour(s)
break
### TODO : a ameliorer car bad_filename_path_flag ne prend pas en compte python_path.
### relechir sur comment faire en sorte de ne pas donner la main a la simulation
### en fonction de la validite des deux criteres plus bas
### if the path dont exists, background color is red
try:
### if the type of cell is string
if isinstance(val, (str, unicode)):
if col == 1:
v = self.GetValue(row, 0)
### if bad filemane (for instance generator)
m = re.match('[a-zA-Z]*(ile)[n|N](ame)[_-a-zA-Z0-9]*', v, re.IGNORECASE)
### if filename is match and not exist (ensuring that the filename are extension)
if m is not None and not os.path.exists(self.GetValue(row, 1)) and os.path.splitext(self.GetValue(row, 1))[-1] != '':
self.bad_flag.update({v:False})
attr.SetBackgroundColour("pink")
### if the python path is not found
if v == "python_path":
### si un le modèle est un fichier python et que le path n'existe pas ou si c'est un amd ou cmd et que le fichier modèle n'existe pas
if (not os.path.exists(self.model.python_path) and not zipfile.is_zipfile(self.model.model_path)) or\
(not os.path.exists(self.model.model_path) and zipfile.is_zipfile(self.model.model_path)):
self.bad_flag.update({v:False})
attr.SetBackgroundColour("pink")
return attr
except Exception, info:
sys.stderr.write(_('Error in GetAttr : %s'%info))
return
开发者ID:CelineBateauKessler,项目名称:DEVSimPy,代码行数:58,代码来源:PropertiesGridCtrl.py
示例19: _move_data_file
def _move_data_file(self, saveloc, json_):
"""
- Look at _state attribute of object.
- Find all fields with 'isdatafile' attribute as True.
- If there is a key in json_ corresponding with
'name' of the fields with True 'isdatafile' attribute
- then
- move that datafile and
- update the key in the json_ to point to new location
"""
fields = self._state.get_field_by_attribute('isdatafile')
for field in fields:
if field.name not in json_:
continue
raw_paths = json_[field.name]
if isinstance(raw_paths, list):
for i, p in enumerate(raw_paths):
d_fname = os.path.split(p)[1]
if zipfile.is_zipfile(saveloc):
# add datafile to zip archive
with zipfile.ZipFile(saveloc, 'a',
compression=zipfile.ZIP_DEFLATED,
allowZip64=self._allowzip64) as z:
if d_fname not in z.namelist():
z.write(p, d_fname)
else:
# move datafile to saveloc
if p != os.path.join(saveloc, d_fname):
shutil.copy(p, saveloc)
# always want to update the reference so it is relative
# to saveloc
json_[field.name][i] = d_fname
else:
# data filename
d_fname = os.path.split(json_[field.name])[1]
if zipfile.is_zipfile(saveloc):
# add datafile to zip archive
with zipfile.ZipFile(saveloc, 'a',
compression=zipfile.ZIP_DEFLATED,
allowZip64=self._allowzip64) as z:
if d_fname not in z.namelist():
z.write(json_[field.name], d_fname)
else:
# move datafile to saveloc
if json_[field.name] != os.path.join(saveloc, d_fname):
shutil.copy(json_[field.name], saveloc)
# always want to update the reference so it is relative
# to saveloc
json_[field.name] = d_fname
return json_
开发者ID:NOAA-ORR-ERD,项目名称:PyGnome,代码行数:58,代码来源:save_load.py
示例20: main
def main():
parser = argparse.ArgumentParser(description='Manipulate Comic Book archives (split, extract, trim)')
ops_group = parser.add_mutually_exclusive_group()
parser.add_argument('input', help="Path to comic book archive (cbz/cbr/zip/rar). Multiple files for join are allowed", default=None, nargs="+")
ops_group.add_argument('-j', '--join', help="Join input files in specified order", action="store_true", default=False)
ops_group.add_argument('-x', '--extract', help="Extract ranges to new archive. Format 3,4,10-19")
parser.add_argument('-r', '--resize', help="Resize images e.g. 1600x1200, x1200 (height only), 1600x (width only) ", default=None)
parser.add_argument('-f', '--iformat', help="Convert images to formart (png/jpg)", default=None)
parser.add_argument('-o', '--output', help="Output filename")
args=parser.parse_args()
if args.join is True:
for file in args.input:
if not zipfile.is_zipfile(file):
print ("ERROR! Invalid zip file - ", file)
sys.exit(-1)
if args.output is None:
args.output = generate_archive_name(args.input[0])
if get_user_confirmation("Join files and create new archive?"):
join_selected_archives(args.input, args.output)
elif args.input is not None:
if len(args.input) > 1:
print ("More than one input file specified. This is valid only with -j/--join switch.")
sys.exit(-1)
comic_file = args.input[0]
if zipfile.is_zipfile(comic_file):
sorted_files = get_sorted_filelist(comic_file)
#print ("Files in archive (Excl. directories) - ", len(sorted_files))
if args.output is None:
args.output = generate_archive_name(comic_file)
if args.extract is not None:
pages_2_extract = parse_range(args.extract, len(sorted_files))
if len(pages_2_extract.keys()) == 0:
print ("Invalid range specification")
else:
graphic = page_range_graphic(pages_2_extract, len(sorted_files))
print ("\n{} of {} pages will be extracted\n\n{}\n".format(len(pages_2_extract), len(sorted_files), graphic))
count = 0
selected_pages = []
for file in sorted_files:
count += 1
if count in pages_2_extract:
selected_pages.append(file)
#print ("Selected Pages - ", selected_pages)
if get_user_confirmation("Extract files and create new archive?"):
create_archive_from_extracted(comic_file, args.output, selected_pages, args.resize, args.iformat)
elif args.resize or args.iformat is not None:
if get_user_confirmation("Process files and create new archive?"):
create_archive_from_extracted(comic_file, args.output, sorted_files, args.resize, args.iformat)
else:
print ("ERROR! Invalid zip file - ", comic_file)
print ("Done!\n")
开发者ID:imdn,项目名称:scripts,代码行数:58,代码来源:comic-tool.py
注:本文中的zipfile.is_zipfile函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论