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


Python path.splitext方法代码示例

本文整理汇总了Python中os.path.splitext方法的典型用法代码示例。如果您正苦于以下问题:Python path.splitext方法的具体用法?Python path.splitext怎么用?Python path.splitext使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os.path的用法示例。


在下文中一共展示了path.splitext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def __init__(self, spec_url):
        """Create a new URLLoader.

        Keyword arguments:
        spec_url -- URL where the specification YAML file is located."""
        headers = {'Accept' : 'text/yaml'}
        resp = requests.get(spec_url, headers=headers)
        if resp.status_code == 200:
            self.spec = yaml.load(resp.text)
            self.spec['url'] = spec_url
            self.spec['files'] = {}
            for queryUrl in self.spec['queries']:
                queryNameExt = path.basename(queryUrl)
                queryName = path.splitext(queryNameExt)[0] # Remove extention
                item = {
                    'name': queryName,
                    'download_url': queryUrl
                }
                self.spec['files'][queryNameExt] = item
            del self.spec['queries']
        else:
            raise Exception(resp.text) 
开发者ID:CLARIAH,项目名称:grlc,代码行数:24,代码来源:fileLoaders.py

示例2: build_index

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def build_index():
    repo_directory = get_config()['repo_directory']
    index_path = path.join(repo_directory, 'pages', 'index.json')
    page_path = path.join(repo_directory, 'pages')

    tree_generator = os.walk(page_path)
    folders = next(tree_generator)[1]
    commands, new_index = {}, {}
    for folder in folders:
        pages = next(tree_generator)[2]
        for page in pages:
            command_name = path.splitext(page)[0]
            if command_name not in commands:
                commands[command_name] = {'name': command_name,
                                          'platform': [folder]}
            else:
                commands[command_name]['platform'].append(folder)
    command_list = [item[1] for item in
                    sorted(commands.items(), key=itemgetter(0))]
    new_index['commands'] = command_list

    with open(index_path, mode='w') as f:
        json.dump(new_index, f) 
开发者ID:lord63,项目名称:tldr.py,代码行数:25,代码来源:cli.py

示例3: __getitem__

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def __getitem__(self, index):
        datafiles = self.files[index]
        image = cv2.imread(datafiles["img"], cv2.IMREAD_COLOR)
        size = image.shape
        name = osp.splitext(osp.basename(datafiles["img"]))[0]
        image = np.asarray(image, np.float32)
        image -= self.mean
        
        img_h, img_w, _ = image.shape
        pad_h = max(self.crop_h - img_h, 0)
        pad_w = max(self.crop_w - img_w, 0)
        if pad_h > 0 or pad_w > 0:
            image = cv2.copyMakeBorder(image, 0, pad_h, 0, 
                pad_w, cv2.BORDER_CONSTANT, 
                value=(0.0, 0.0, 0.0))
        image = image.transpose((2, 0, 1))
        return image, name, size 
开发者ID:speedinghzl,项目名称:pytorch-segmentation-toolbox,代码行数:19,代码来源:datasets.py

示例4: __init__

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def __init__(self, root, list_path, crop_size=(505, 505), mean=(128, 128, 128)):
        self.root = root
        self.list_path = list_path
        self.crop_h, self.crop_w = crop_size
        self.mean = mean
        # self.mean_bgr = np.array([104.00698793, 116.66876762, 122.67891434])
        self.img_ids = [i_id.strip().split() for i_id in open(list_path)]
        self.files = [] 
        # for split in ["train", "trainval", "val"]:
        for item in self.img_ids:
            image_path, label_path = item
            name = osp.splitext(osp.basename(label_path))[0]
            img_file = osp.join(self.root, image_path)
            self.files.append({
                "img": img_file
            }) 
开发者ID:speedinghzl,项目名称:pytorch-segmentation-toolbox,代码行数:18,代码来源:datasets.py

示例5: load

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def load(self, file, name=None):
        """Load a file. The format name can be specified explicitly or
        inferred from the file extension."""
        if name is None:
            name = self.format_from_extension(op.splitext(file)[1])
        file_format = self.file_type(name)
        if file_format == 'text':
            return _read_text(file)
        elif file_format == 'json':
            return _read_json(file)
        else:
            load_function = self._formats[name].get('load', None)
            if load_function is None:
                raise IOError("The format must declare a file type or "
                              "load/save functions.")
            return load_function(file) 
开发者ID:rossant,项目名称:ipymd,代码行数:18,代码来源:format_manager.py

示例6: save

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def save(self, file, contents, name=None, overwrite=False):
        """Save contents into a file. The format name can be specified
        explicitly or inferred from the file extension."""
        if name is None:
            name = self.format_from_extension(op.splitext(file)[1])
        file_format = self.file_type(name)
        if file_format == 'text':
            _write_text(file, contents)
        elif file_format == 'json':
            _write_json(file, contents)
        else:
            write_function = self._formats[name].get('save', None)
            if write_function is None:
                raise IOError("The format must declare a file type or "
                              "load/save functions.")
            if op.exists(file) and not overwrite:
                print("The file already exists, please use overwrite=True.")
                return
            write_function(file, contents) 
开发者ID:rossant,项目名称:ipymd,代码行数:21,代码来源:format_manager.py

示例7: register_plugins

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def register_plugins(linter, directory):
    """load all module and package in the given directory, looking for a
    'register' function in each one, used to register pylint checkers
    """
    imported = {}
    for filename in os.listdir(directory):
        base, extension = splitext(filename)
        if base in imported or base == '__pycache__':
            continue
        if extension in PY_EXTS and base != '__init__' or (
                not extension and isdir(join(directory, base))):
            try:
                module = modutils.load_module_from_file(join(directory, filename))
            except ValueError:
                # empty module name (usually emacs auto-save files)
                continue
            except ImportError as exc:
                print("Problem importing module %s: %s" % (filename, exc),
                      file=sys.stderr)
            else:
                if hasattr(module, 'register'):
                    module.register(linter)
                    imported[base] = 1 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:25,代码来源:utils.py

示例8: __init__

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def __init__(self, in_dir, transform):
        super(ISSTestDataset, self).__init__()
        self.in_dir = in_dir
        self.transform = transform

        # Find all images
        self._images = []
        for img_path in chain(
                *(glob.iglob(path.join(self.in_dir, '**', ext), recursive=True) for ext in ISSTestDataset._EXTENSIONS)):
            _, name_with_ext = path.split(img_path)
            idx, _ = path.splitext(name_with_ext)

            with Image.open(img_path) as img_raw:
                size = (img_raw.size[1], img_raw.size[0])

            self._images.append({
                "idx": idx,
                "path": img_path,
                "size": size,
            }) 
开发者ID:mapillary,项目名称:seamseg,代码行数:22,代码来源:dataset.py

示例9: save_prediction_raw

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def save_prediction_raw(raw_pred, _, img_info, out_dir):
    # Prepare folders and paths
    folder, img_name = path.split(img_info["rel_path"])
    img_name, _ = path.splitext(img_name)
    out_dir = path.join(out_dir, folder)
    ensure_dir(out_dir)
    out_path = path.join(out_dir, img_name + ".pth.tar")

    out_data = {
        "sem_pred": raw_pred[0],
        "bbx_pred": raw_pred[1],
        "cls_pred": raw_pred[2],
        "obj_pred": raw_pred[3],
        "msk_pred": raw_pred[4]
    }
    torch.save(out_data, out_path) 
开发者ID:mapillary,项目名称:seamseg,代码行数:18,代码来源:test_panoptic.py

示例10: py_compile

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def py_compile(node, filename='<unknown>', is_entrypoint=False):
    if isinstance(node, Tag):
        ctx = _non_ctx.enter_new(node.tag)
        ctx.bc.filename = filename
        ctx.bc.name = '__main__' if is_entrypoint else splitext(
            Path(filename).relative())[0]
        try:
            py_emit(node.it, ctx)
        except SyntaxError as exc:
            exc.filename = filename
            raise exc
        return ctx.bc.to_code()
        # try:
        #     return ctx.bc.to_code()
        # except Exception as e:
        #     dump_bytecode(ctx.bc)
        #     raise e
    else:
        tag = to_tagged_ast(node)
        return py_compile(tag, filename, is_entrypoint=is_entrypoint) 
开发者ID:Xython,项目名称:YAPyPy,代码行数:22,代码来源:py_compile.py

示例11: get_syntax_alias

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def get_syntax_alias(filename):
    """ return an alias based on the filename that is used to
        override the automatic syntax highlighting dectection
        by highlight.js
    """

    override_rules = pagure_config.get(
        "SYNTAX_ALIAS_OVERRIDES",
        {".spec": "rpm-specfile", ".patch": "diff", ".adoc": "asciidoc"},
    )
    fn, fn_ext = splitext(filename)

    output = ""
    if fn_ext == "":
        output = "lang-plaintext"
    elif fn_ext in override_rules:
        output = "lang-" + override_rules[fn_ext]

    return output 
开发者ID:Pagure,项目名称:pagure,代码行数:21,代码来源:filters.py

示例12: _init_state

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def _init_state(self):
        """Bind device to the physical layer API."""

        subpath, extension = splitext(self.state['path'])

        if extension == '.sqlite':
            # TODO: add parametric value filed
            # print 'DEBUG state: ', self.state
            self._state = SQLiteState(self.state)
        elif extension == '.redis':
            # TODO: add parametric key serialization
            self._state = RedisState(self.state)
        else:
            print 'ERROR: %s backend not supported.' % self.state

    # TODO: add optional process name for the server and log location 
开发者ID:scy-phy,项目名称:minicps,代码行数:18,代码来源:devices.py

示例13: _check_if_pyc

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def _check_if_pyc(fname):
    """Return True if the extension is .pyc, False if .py
    and None if otherwise"""
    from imp import find_module
    from os.path import realpath, dirname, basename, splitext

    # Normalize the file-path for the find_module()
    filepath = realpath(fname)
    dirpath = dirname(filepath)
    module_name = splitext(basename(filepath))[0]

    # Validate and fetch
    try:
        fileobj, fullpath, (_, _, pytype) = find_module(module_name, [dirpath])
    except ImportError:
        raise IOError("Cannot find config file. "
                      "Path maybe incorrect! : {0}".format(filepath))
    return pytype, fileobj, fullpath 
开发者ID:jpush,项目名称:jbox,代码行数:20,代码来源:_compat.py

示例14: _parse_file

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def _parse_file(self, filename, file_url):
        """
        Attempts to parse a file with the loaded plugins
        Returns set of endpoints
        """
        file_set = set()
        with open(filename, 'r') as plug_in:
            lines = plug_in.readlines()
        ext = path.splitext(filename)[1].upper()
        if ext in self.plugins.keys() and self._ext_test(ext):
            for plug in self.plugins.get(ext):
                if plug.enabled:
                    res = plug.run(lines)
                    if len(res) > 0:
                        for i in res:
                            i = file_url + i
                            file_set.add(i)
        elif ext == '.TXT' and self._ext_test(ext):
            for i in lines:
                i = file_url + i
                file_set.add(i.strip())
        return file_set 
开发者ID:aur3lius-dev,项目名称:SpyDir,代码行数:24,代码来源:SpyDir.py

示例15: get_extension

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import splitext [as 别名]
def get_extension(url, response):

    from os.path import splitext

    filename = url2name(url)
    if 'Content-Disposition' in response.info():
        cd_list = response.info()['Content-Disposition'].split('filename=')
        if len(cd_list) > 1:
            filename = cd_list[-1]
            if filename[0] == '"' or filename[0] == "'":
                filename = filename[1:-1]
    elif response.url != url:
        filename = url2name(response.url)
    ext = splitext(filename)[1][1:]
    if not ext:
        ext = 'mp4'
    return ext 
开发者ID:bugatsinho,项目名称:bugatsinho.github.io,代码行数:19,代码来源:client.py


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