当前位置: 首页>>代码示例>>Python>>正文


Python path.isfile方法代码示例

本文整理汇总了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 
开发者ID:Gurux,项目名称:Gurux.DLMS.Python,代码行数:26,代码来源:GXManufacturerCollection.py

示例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.
    # 
开发者ID:Gurux,项目名称:Gurux.DLMS.Python,代码行数:22,代码来源:GXManufacturerCollection.py

示例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} 
开发者ID:lingluodlut,项目名称:Att-ChemdNER,代码行数:25,代码来源:utils.py

示例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 
开发者ID:open-mmlab,项目名称:mmdetection,代码行数:26,代码来源:pascal_voc.py

示例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 
开发者ID:mh4x0f,项目名称:b1tifi,代码行数:18,代码来源:ssh.py

示例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 
开发者ID:calmjs,项目名称:calmjs,代码行数:24,代码来源:toolchain.py

示例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 
开发者ID:awslabs,项目名称:aws-ops-automator,代码行数:24,代码来源:__init__.py

示例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 
开发者ID:awslabs,项目名称:aws-ops-automator,代码行数:18,代码来源:__init__.py

示例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 
开发者ID:awslabs,项目名称:aws-ops-automator,代码行数:26,代码来源:__init__.py

示例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)) 
开发者ID:rtlee9,项目名称:recipe-box,代码行数:18,代码来源:get_pictures.py

示例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') 
开发者ID:ShahriyarR,项目名称:MySQL-AutoXtraBackup,代码行数:19,代码来源:prepare.py

示例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.") 
开发者ID:ShahriyarR,项目名称:MySQL-AutoXtraBackup,代码行数:18,代码来源:backuper.py

示例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 
开发者ID:bilelmoussaoui,项目名称:Authenticator,代码行数:21,代码来源:qr_reader.py

示例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) 
开发者ID:menpo,项目名称:landmarkerio-server,代码行数:21,代码来源:template.py

示例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 
开发者ID:rafasashi,项目名称:razzy-spinner,代码行数:19,代码来源:senna.py


注:本文中的os.path.isfile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。