本文整理汇总了Python中os.path方法的典型用法代码示例。如果您正苦于以下问题:Python os.path方法的具体用法?Python os.path怎么用?Python os.path使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.path方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: scan
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def scan(self, path, exclude=[]) -> List[str]:
"""Scan path for matching files.
:param path: the path to scan
:param exclude: a list of directories to exclude
:return: a list of sorted filenames
"""
res = []
path = path.rstrip("/").rstrip("\\")
for pat in self.input_patterns:
res.extend(glob.glob(path + os.sep + pat, recursive=True))
res = list(filter(lambda p: os.path.isfile(p), res))
if exclude:
def excluded(path):
for e in exclude:
if path.startswith(e):
return True
return False
res = list(filter(lambda p: not excluded(p), res))
return sorted(res)
示例2: _save
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def _save(model, base_model, layers, labels, random_seed, checkpoints_dir):
from keras.layers import Flatten, Dense
from keras import Model
nclasses = len(labels)
x = Flatten()(base_model.output)
x = _makenet(x, layers, dropout=None, random_seed=random_seed)
predictions = Dense(nclasses, activation="softmax", name="predictions")(x)
model_final = Model(inputs=base_model.input, outputs=predictions)
for i in range(layers - 1):
weights = model.get_layer(name='dense_layer_{}'.format(i)).get_weights()
model_final.get_layer(name='dense_layer_{}'.format(i)).set_weights(weights)
weights = model.get_layer(name='predictions').get_weights()
model_final.get_layer(name='predictions').set_weights(weights)
model_final.save(os.path.join(checkpoints_dir, "model.h5"))
with open(os.path.join(checkpoints_dir, "labels.txt"), "w") as f:
f.write("\n".join(labels))
return model_final
示例3: preview_filename
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def preview_filename(self, path):
"""Generate a filename for previews, appending a number when the file already exists.
"""
if not os.path.exists(path):
return path
pcounter = SourcePlugin._COUNTER
if not path in pcounter:
pcounter[path] = 1
fname, ext = os.path.splitext(path)
counter = pcounter[path]
while os.path.exists("{}_{}{}".format(fname, counter, ext)):
counter += 1
pcounter[path] = counter
return "{}_{}{}".format(fname, counter, ext)
示例4: load
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def load(self, model_dir, architecture, image_size):
from keras.models import load_model
from vergeml.sources.features import get_preprocess_input
labels_txt = os.path.join(model_dir, "labels.txt")
if not os.path.exists(labels_txt):
raise VergeMLError("labels.txt not found: {}".format(labels_txt))
model_h5 = os.path.join(model_dir, "model.h5")
if not os.path.exists(model_h5):
raise VergeMLError("model.h5 not found: {}".format(model_h5))
with open(labels_txt, "r") as f:
self.labels = f.read().splitlines()
self.model = load_model(model_h5)
self.image_size = image_size
self.preprocess_input = get_preprocess_input(architecture)
示例5: predict
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def predict(self, f, k=5, resize_mode='fill'):
from keras.preprocessing import image
from vergeml.img import resize_image
filename = os.path.basename(f)
if not os.path.exists(f):
return dict(filename=filename, prediction=[])
img = image.load_img(f)
img = resize_image(img, self.image_size, self.image_size, 'antialias', resize_mode)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = self.preprocess_input(x)
preds = self.model.predict(x)
pred = self._decode(preds, top=k)[0]
prediction=[dict(probability=np.asscalar(perc), label=klass) for _, klass, perc in pred]
return dict(filename=filename, prediction=prediction)
示例6: _validate_split
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def _validate_split(self, project_dir):
"""Validate the split configuration for val and test.
"""
for split in ('val-split', 'test-split'):
spltype, splval = parse_split(self._config[split])
if spltype == 'dir':
# deal with relative paths
path = os.path.join(project_dir, splval) if not os.path.isabs(splval) else splval
if not os.path.exists(path):
# raise if path does not exist
msg = f"Invalid value for option {split} - no such directory: {splval}"
suggestion = f"Please set {split} to a percentage, number or directory."
raise VergeMLError(msg, suggestion,
hint_key=split, hint_type='value', help_topic='split')
示例7: _load_trained_model
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def _load_trained_model(self):
"""Load a trained models hyperparameters and results
"""
train_mod_path = os.path.join(self._config['trainings-dir'], self.trained_model)
if not os.path.exists(train_mod_path):
raise VergeMLError("Trained model not found: {}".format(self.trained_model))
# Merge data.yaml
data_file = os.path.join(self._config['trainings-dir'], self.trained_model, 'data.yaml')
if not os.path.exists(data_file):
raise VergeMLError("data.yaml file not found for {}: {}".format(
self.trained_model, data_file))
doc = load_yaml_file(data_file, 'data file')
self._config.update({
'hyperparameters': doc.get('hyperparameters', {}),
'results': doc.get('results', {}),
'model': doc.get('model')
})
self.results = _Results(self, data_file)
return data_file
示例8: get_custom_architecture
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def get_custom_architecture(name, trainings_dir, output_layer):
from keras.models import load_model, Model
name = name.lstrip("@")
model = load_model(os.path.join(trainings_dir, name, 'checkpoints', 'model.h5'))
try:
if isinstance(output_layer, int):
layer = model.layers[output_layer]
else:
layer = model.get_layer(output_layer)
except Exception:
if isinstance(output_layer, int):
raise VergeMLError(f'output-layer {output_layer} not found - model has only {len(model.layers)} layers.')
else:
candidates = list(map(lambda l: l.name, model.layers))
raise VergeMLError(f'output-layer named {output_layer} not found.',
suggestion=did_you_mean(candidates, output_layer))
model = Model(inputs=model.input, outputs=layer.output)
return model
示例9: load_predictions
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def load_predictions(env, nclasses):
path = os.path.join(env.stats_dir(), "predictions.csv")
if not os.path.exists(path):
raise FileExistsError(path)
with open(path, newline='') as csvfile:
y_score = []
y_test = []
csv_reader = csv.reader(csvfile, dialect="excel")
for row in csv_reader:
assert len(row) == nclasses * 2
y_score.append(list(map(float, row[:nclasses])))
y_test.append(list(map(float, row[nclasses:])))
y_score = np.array(y_score)
y_test = np.array(y_test)
return y_test, y_score
示例10: __call__
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def __call__(self, args, env):
samples_dir = env.get('samples-dir')
print("Downloading unique objects to {}.".format(samples_dir))
src_dir = self.download_files([_URL], env=env, dir=env.get('cache-dir'))
path = os.path.join(src_dir, "ObjectsAll.zip")
zipf = zipfile.ZipFile(path, 'r')
zipf.extractall(src_dir)
zipf.close()
for file in os.listdir(os.path.join(src_dir, "OBJECTSALL")):
shutil.copy(os.path.join(src_dir, "OBJECTSALL", file), samples_dir)
shutil.rmtree(src_dir)
print("Finished downloading unique objects.")
示例11: add_base_arguments
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def add_base_arguments(parser, default_help):
import os
from os.path import join as path_join
home = os.environ.get('HOME')
mono_sources_default = os.environ.get('MONO_SOURCE_ROOT', '')
parser.add_argument('--verbose-make', action='store_true', default=False, help=default_help)
# --jobs supports not passing an argument, in which case the 'const' is used,
# which is the number of CPU cores on the host system.
parser.add_argument('--jobs', '-j', nargs='?', const=str(os.cpu_count()), default='1', help=default_help)
parser.add_argument('--configure-dir', default=path_join(home, 'mono-configs'), help=default_help)
parser.add_argument('--install-dir', default=path_join(home, 'mono-installs'), help=default_help)
if mono_sources_default:
parser.add_argument('--mono-sources', default=mono_sources_default, help=default_help)
else:
parser.add_argument('--mono-sources', required=True)
parser.add_argument('--mxe-prefix', default='/usr', help=default_help)
示例12: find_executable
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def find_executable(name) -> str:
is_windows = os.name == 'nt'
windows_exts = os.environ['PATHEXT'].split(ENV_PATH_SEP) if is_windows else None
path_dirs = os.environ['PATH'].split(ENV_PATH_SEP)
search_dirs = path_dirs + [os.getcwd()] # cwd is last in the list
for dir in search_dirs:
path = os.path.join(dir, name)
if is_windows:
for extension in windows_exts:
path_with_ext = path + extension
if os.path.isfile(path_with_ext) and os.access(path_with_ext, os.X_OK):
return path_with_ext
else:
if os.path.isfile(path) and os.access(path, os.X_OK):
return path
return ''
示例13: configure
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def configure(opts: AndroidOpts, product: str, target: str):
env = { 'ANDROID_API_VERSION': get_api_version_or_min(opts, target) }
if is_cross(target):
import llvm
if is_cross_mxe(target):
llvm.make(opts, 'llvmwin64')
setup_android_cross_mxe_template(env, opts, target, host_arch='x86_64')
else:
llvm.make(opts, 'llvm64')
setup_android_cross_template(env, opts, target, host_arch='x86_64')
else:
make_standalone_toolchain(opts, target, env['ANDROID_API_VERSION'])
setup_android_target_template(env, opts, target)
if not os.path.isfile(path_join(opts.mono_source_root, 'configure')):
runtime.run_autogen(opts)
runtime.run_configure(env, opts, product, target)
示例14: import_helper
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def import_helper():
from os.path import dirname
import imp
possible_libs = ["_alf_grammar.win32",
"_alf_grammar.ntoarm",
"_alf_grammar.ntox86",
"_alf_grammar.linux"]
found_lib = False
for i in possible_libs:
fp = None
try:
fp, pathname, description = imp.find_module(i, [dirname(__file__)])
_mod = imp.load_module("_alf_grammar", fp, pathname, description)
found_lib = True
break
except ImportError:
pass
finally:
if fp:
fp.close()
if not found_lib:
raise ImportError("Failed to load _alf_grammar module")
return _mod
示例15: cachedir
# 需要导入模块: import os [as 别名]
# 或者: from os import path [as 别名]
def cachedir(self):
"""Path to workflow's cache directory.
The cache directory is a subdirectory of Alfred's own cache directory
in ``~/Library/Caches``. The full path is:
``~/Library/Caches/com.runningwithcrayons.Alfred-X/Workflow Data/<bundle id>``
``Alfred-X`` may be ``Alfred-2`` or ``Alfred-3``.
:returns: full path to workflow's cache directory
:rtype: ``unicode``
"""
if self.alfred_env.get('workflow_cache'):
dirpath = self.alfred_env.get('workflow_cache')
else:
dirpath = self._default_cachedir
return self._create(dirpath)