當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。