本文整理匯總了Python中os.path.isfile方法的典型用法代碼示例。如果您正苦於以下問題:Python path.isfile方法的具體用法?Python path.isfile怎麽用?Python path.isfile使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類os.path
的用法示例。
在下文中一共展示了path.isfile方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: isUpdatesAvailable
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def isUpdatesAvailable(cls, path):
if sys.version_info < (3, 0):
return False
# pylint: disable=broad-except
if not os.path.isfile(os.path.join(path, "files.xml")):
return True
try:
available = dict()
for it in ET.parse(os.path.join(path, "files.xml")).iter():
if it.tag == "File":
available[it.text] = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")
path = NamedTemporaryFile()
path.close()
urllib.request.urlretrieve("https://www.gurux.fi/obis/files.xml", path.name)
for it in ET.parse(path.name).iter():
if it.tag == "File":
tmp = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")
if not it.text in available or available[it.text] != tmp:
return True
except Exception as e:
print(e)
return True
return False
示例2: readManufacturerSettings
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def readManufacturerSettings(cls, manufacturers, path):
# pylint: disable=broad-except
manufacturers = []
files = [f for f in listdir(path) if isfile(join(path, f))]
if files:
for it in files:
if it.endswith(".obx"):
try:
manufacturers.append(cls.__parse(os.path.join(path, it)))
except Exception as e:
print(e)
continue
#
# Serialize manufacturer from the xml.
#
# @param in
# Input stream.
# Serialized manufacturer.
#
示例3: get_perf
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def get_perf(filename):
''' run conlleval.pl perl script to obtain
precision/recall and F1 score '''
_conlleval = PREFIX + 'conlleval'
if not isfile(_conlleval):
#download('http://www-etud.iro.umontreal.ca/~mesnilgr/atis/conlleval.pl')
os.system('wget https://www.comp.nus.edu.sg/%7Ekanmy/courses/practicalNLP_2008/packages/conlleval.pl')
chmod('conlleval.pl', stat.S_IRWXU) # give the execute permissions
out = []
proc = subprocess.Popen(["perl", _conlleval], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, _ = proc.communicate(open(filename).read())
for line in stdout.split('\n'):
if 'accuracy' in line:
out = line.split()
break
# out = ['accuracy:', '16.26%;', 'precision:', '0.00%;', 'recall:', '0.00%;', 'FB1:', '0.00']
precision = float(out[3][:-2])
recall = float(out[5][:-2])
f1score = float(out[7])
return {'p':precision, 'r':recall, 'f1':f1score}
示例4: cvt_annotations
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def cvt_annotations(devkit_path, years, split, out_file):
if not isinstance(years, list):
years = [years]
annotations = []
for year in years:
filelist = osp.join(devkit_path,
f'VOC{year}/ImageSets/Main/{split}.txt')
if not osp.isfile(filelist):
print(f'filelist does not exist: {filelist}, '
f'skip voc{year} {split}')
return
img_names = mmcv.list_from_file(filelist)
xml_paths = [
osp.join(devkit_path, f'VOC{year}/Annotations/{img_name}.xml')
for img_name in img_names
]
img_paths = [
f'VOC{year}/JPEGImages/{img_name}.jpg' for img_name in img_names
]
part_annotations = mmcv.track_progress(parse_xml,
list(zip(xml_paths, img_paths)))
annotations.extend(part_annotations)
mmcv.dump(annotations, out_file)
return annotations
示例5: ThreadSSH
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def ThreadSSH(self):
try:
self.session = pxssh.pxssh(encoding='utf-8')
if (not path.isfile(self.settings['Password'])):
self.session.login(gethostbyname(self.settings['Host']), self.settings['User'],
self.settings['Password'],port=self.settings['Port'])
else:
self.session.login(gethostbyname(self.settings['Host']), self.settings['User'],
ssh_key=self.settings['Password'],port=self.settings['Port'])
if self.connection:
self.status = '[{}]'.format(setcolor('ON',color='green'))
self.activated = True
except Exception, e:
self.status = '[{}]'.format(setcolor('OFF',color='red'))
self.activated = False
示例6: compile_bundle_entry
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def compile_bundle_entry(self, spec, entry):
"""
Handler for each entry for the bundle method of the compile
process. This copies the source file or directory into the
build directory.
"""
modname, source, target, modpath = entry
bundled_modpath = {modname: modpath}
bundled_target = {modname: target}
export_module_name = []
if isfile(source):
export_module_name.append(modname)
copy_target = join(spec[BUILD_DIR], target)
if not exists(dirname(copy_target)):
makedirs(dirname(copy_target))
shutil.copy(source, copy_target)
elif isdir(source):
copy_target = join(spec[BUILD_DIR], modname)
shutil.copytree(source, copy_target)
return bundled_modpath, bundled_target, export_module_name
示例7: all_actions
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def all_actions():
"""
Returns a list of all available actions from the *.py files in the actions directory
:return: ist of all available action
"""
result = []
directory = os.getcwd()
while True:
if any([entry for entry in listdir(directory) if entry == ACTIONS_DIR and isdir(os.path.join(directory, entry))]):
break
directory = os.path.abspath(os.path.join(directory, '..'))
actions_dir = os.path.join(directory, ACTIONS_DIR)
for f in listdir(actions_dir):
if isfile(join(actions_dir, f)) and f.endswith("_{}.py".format(ACTION.lower())):
module_name = ACTION_MODULE_NAME.format(f[0:-len(".py")])
mod = get_action_module(module_name)
cls = _get_action_class_from_module(mod)
if cls is not None:
action_name = cls[0][0:-len(ACTION)]
result.append(action_name)
return result
示例8: all_services
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def all_services():
"""
Return as list of all supported service names
:return: list of all supported service names
"""
result = []
for f in listdir(SERVICES_PATH):
if isfile(join(SERVICES_PATH, f)) and f.endswith("_{}.py".format(SERVICE.lower())):
module_name = SERVICE_MODULE_NAME.format(f[0:-len(".py")])
service_module = _get_module(module_name)
cls = _get_service_class(service_module)
if cls is not None:
service_name = cls[0][0:-len(SERVICE)]
if service_name.lower() != "aws":
result.append(service_name)
return result
示例9: all_handlers
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def all_handlers():
global __actions
if __actions is None:
__actions = []
current = abspath(os.getcwd())
while True:
if isdir(os.path.join(current, "handlers")):
break
parent = dirname(current)
if parent == current:
# at top level
raise Exception("Could not find handlers directory")
else:
current = parent
for f in listdir(os.path.join(current, "handlers")):
if isfile(join(current, "handlers", f)) and f.endswith("_{}.py".format(HANDLER.lower())):
module_name = HANDLERS_MODULE_NAME.format(f[0:-len(".py")])
m = _get_module(module_name)
cls = _get_handler_class(m)
if cls is not None:
handler_name = cls[0]
__actions.append(handler_name)
return __actions
示例10: save_picture
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def save_picture(recipes_raw, url):
recipe = recipes_raw[url]
path_save = path.join(
config.path_img, '{}.jpg'.format(URL_to_filename(url)))
if not path.isfile(path_save):
if 'picture_link' in recipe:
link = recipe['picture_link']
if link is not None:
try:
if 'epicurious' in url:
img_url = 'https://{}'.format(link[2:])
urllib.request.urlretrieve(img_url, path_save)
else:
urllib.request.urlretrieve(link, path_save)
except:
print('Could not download image from {}'.format(link))
示例11: parse_backup_tags
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def parse_backup_tags(backup_dir, tag_name):
"""
Static Method for returning the backup directory name and backup type
:param backup_dir: The backup directory path
:param tag_name: The tag name to search
:return: Tuple of (backup directory, backup type) (2017-11-09_19-37-16, Full).
:raises: RuntimeError if there is no such tag inside backup_tags.txt
"""
if os.path.isfile("{}/backup_tags.txt".format(backup_dir)):
with open('{}/backup_tags.txt'.format(backup_dir), 'r') as bcktags:
f = bcktags.readlines()
for i in f:
splitted = i.split('\t')
if tag_name == splitted[-1].rstrip("'\n\r").lstrip("'"):
return splitted[0], splitted[1]
raise RuntimeError('There is no such tag for backups')
示例12: show_tags
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def show_tags(backup_dir):
if os.path.isfile("{}/backup_tags.txt".format(backup_dir)):
with open('{}/backup_tags.txt'.format(backup_dir), 'r') as bcktags:
from_file = bcktags.read()
column_names = "{0}\t{1}\t{2}\t{3}\t{4}\tTAG\n".format(
"Backup".ljust(19),
"Type".ljust(4),
"Status".ljust(2),
"Completion_time".ljust(19),
"Size")
extra_str = "{}\n".format("-"*(len(column_names)+21))
print(column_names + extra_str + from_file)
logger.info(column_names + extra_str + from_file)
else:
logger.warning("Could not find backup_tags.txt inside given backup directory. Can't print tags.")
print("WARNING: Could not find backup_tags.txt inside given backup directory. Can't print tags.")
示例13: read
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def read(self):
try:
from PIL import Image
from pyzbar.pyzbar import decode
decoded_data = decode(Image.open(self.filename))
if path.isfile(self.filename):
remove(self.filename)
try:
url = urlparse(decoded_data[0].data.decode())
query_params = parse_qsl(url.query)
self._codes = dict(query_params)
return self._codes.get("secret")
except (KeyError, IndexError):
Logger.error("Invalid QR image")
return None
except ImportError:
from ..application import Application
Application.USE_QRSCANNER = False
QRReader.ZBAR_FOUND = False
示例14: convert_legacy_template
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def convert_legacy_template(path):
with open(path) as f:
ta = f.read().strip().split('\n\n')
groups = [parse_group(g) for g in ta]
data = {'groups': [group_to_dict(g) for g in groups]}
new_path = path[:-3] + 'yml'
warning = ''
if p.isfile(new_path):
new_path = path[:-4] + '-converted.yml'
warning = '(appended -converted to avoid collision)'
with open(new_path, 'w') as nf:
yaml.dump(data, nf, indent=4, default_flow_style=False)
os.remove(path)
print " - {} > {} {}".format(path, new_path, warning)
示例15: __init__
# 需要導入模塊: from os import path [as 別名]
# 或者: from os.path import isfile [as 別名]
def __init__(self, senna_path, operations, encoding='utf-8'):
self._encoding = encoding
self._path = path.normpath(senna_path) + sep
# Verifies the existence of the executable on the self._path first
#senna_binary_file_1 = self.executable(self._path)
exe_file_1 = self.executable(self._path)
if not path.isfile(exe_file_1):
# Check for the system environment
if 'SENNA' in environ:
#self._path = path.join(environ['SENNA'],'')
self._path = path.normpath(environ['SENNA']) + sep
exe_file_2 = self.executable(self._path)
if not path.isfile(exe_file_2):
raise OSError("Senna executable expected at %s or %s but not found" % (exe_file_1,exe_file_2))
self.operations = operations