• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python path.append函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: GetItemPath

 def GetItemPath(self, item):
     path = []
     while item.IsOk():
         path.append(self._tree.GetPyData(item))
         item = self._tree.GetItemParent(item)
     path.reverse()
     return path
开发者ID:nsmoooose,项目名称:csp,代码行数:7,代码来源:UI.py


示例2: _gen

 def _gen(self, node, path, prefix):
     global args
     tail, heads = self._name_node(path), []
     edges = node.sufs.keys()
     sort = args.sort == "all" or (args.sort == "root" and not path)
     if sort:
         edges.sort()
     for i, edge in enumerate(edges):
         child = node.sufs[edge]
         path.append(i)
         prefix.append(edge)
         self._gen_node(child, path, "".join(prefix))
         head = self._name_node(path)
         if heads and sort:
             self._gen_edge(heads[-1], head, style="invisible", dir="none")
         heads.append(head)
         edge_label = [cgi.escape(edge)]
         edge_attrs = {'label': edge_label, 'tooltip': edge_label}
         if len(path) == 1:
             root = self._name_node([i + len(node.sufs)])
             self._print(root, self._stringify_attrs(style="invisible"))
             self._gen_edge(root + ":e", head + ":w", **edge_attrs)
         else:
             self._gen_edge(tail, head, **edge_attrs)
         self._gen(child, path, prefix)
         path.pop()
         prefix.pop()
     if sort and heads:
         self._print("{ rank=same", " ".join(head for head in heads), "}")
开发者ID:losvald,项目名称:yasnippet-snippets,代码行数:29,代码来源:vis.py


示例3: evaluateTopicPaths

def evaluateTopicPaths(inputFl, pathFl, outputFl, topicId, metric, cutoff):
    profiles = ranking.readInputFl.readInputFl(inputFl, topicId)
    # path files can be quite large, so it opens and processes

    # the path file line-by-line.
    with open(pathFl) as pthFl:
        metricFun = ranking.calcUtilities.getMetricFunction(metric)
        with tempfile.NamedTemporaryFile("r+", delete=False) as tmpF:
            for line in pthFl:
                # 15017299068   1   5  d4 : 0 d4:0 d1:0 d3:1 d2:0
                (usell, ll) = utils.utils.stripComments(line)
                if usell:
                    lline = re.sub("\s:\s", ":", ll)
                    lst = lline.split(None)
                    instId = lst[0]
                    tTopicId = lst[1]
                    if topicId == tTopicId:
                        profileId = lst[2]
                        path = []

                        for dc in lst[3 : len(lst)]:
                            (d, _, c) = dc.partition(":")
                            path.append(d)
                            if profiles.getDocRelMap(profileId) == None:
                                raise Exception("Profile id not found.")
                        docsToRels = dict(profiles.getDocRelMap(profileId))
                        util = metricFun(path, docsToRels, cutoff)
                        tmpF.write(instId + " " + topicId + " " + profileId + " " + str(util) + "\n")
            tmpF.flush()
            tmpF.close()
            shutil.move(tmpF.name, outputFl)
            if os.path.exists(tmpF.name):
                os.remove(tmpF.name)
    return outputFl
开发者ID:joeywen,项目名称:dynamicranking,代码行数:34,代码来源:evaluatePaths.py


示例4: test_func_dir

def test_func_dir(tmpdir):
    # Test the creation of the memory cache directory for the function.
    memory = Memory(location=tmpdir.strpath, verbose=0)
    path = __name__.split('.')
    path.append('f')
    path = tmpdir.join('joblib', *path).strpath

    g = memory.cache(f)
    # Test that the function directory is created on demand
    func_id = _build_func_identifier(f)
    location = os.path.join(g.store_backend.location, func_id)
    assert location == path
    assert os.path.exists(path)
    assert memory.location == os.path.dirname(g.store_backend.location)
    with warns(DeprecationWarning) as w:
        assert memory.cachedir == g.store_backend.location
    assert len(w) == 1
    assert "The 'cachedir' attribute has been deprecated" in str(w[-1].message)

    # Test that the code is stored.
    # For the following test to be robust to previous execution, we clear
    # the in-memory store
    _FUNCTION_HASHES.clear()
    assert not g._check_previous_func_code()
    assert os.path.exists(os.path.join(path, 'func_code.py'))
    assert g._check_previous_func_code()

    # Test the robustness to failure of loading previous results.
    func_id, args_id = g._get_output_identifiers(1)
    output_dir = os.path.join(g.store_backend.location, func_id, args_id)
    a = g(1)
    assert os.path.exists(output_dir)
    os.remove(os.path.join(output_dir, 'output.pkl'))
    assert a == g(1)
开发者ID:joblib,项目名称:joblib,代码行数:34,代码来源:test_memory.py


示例5: random_walk

  def random_walk(self, path_length, alpha=0, rand=random.Random(), start=None):
    """ Returns a truncated random walk.

        path_length: Length of the random walk.
        alpha: probability of restarts.
        start: the start node of the random walk.
    """

    G = self
    if start:
      path = [start]
    else:
      # Sampling is uniform w.r.t V, and not w.r.t E
      path = [rand.choice(G.keys())]

    while len(path) < path_length:
      cur = path[-1]
      if len(G[cur]) > 0:
        if rand.random() >= alpha:
          path.append(rand.choice(G[cur]))
        else:
          path.append(path[0])
      else:
        break
    return path
开发者ID:mehtakash93,项目名称:Graph-Embedding-DeepWalk-Recommender,代码行数:25,代码来源:graph.py


示例6: main

def main():
    output_path = "/Users/ramapriyasridharan/Documents/clients_file.txt"
    path = []
    with open(output_path) as f:
        for exptini_path_raw in f:
            exptini_path = exptini_path_raw.strip()
            path.append(exptini_path)
            print path

    for i in range(6,11):
        print i
        for j in range(0,len(path)):
            print j
            if i < 10:
                p = "/%s/0%d"%(path[j],i)
            else:
                p = "/%s/%d"%(path[j],i)
            print p
            for root, _, files in os.walk(p):
                for f in files:
                    if f.endswith('.tgz'):
                        print 'going to extract %s'%f
                        f1 = os.path.join(p,f)
                        print f1
                        tar = tarfile.open(f1)
                        tar.extractall(p)
                        tar.close()
开发者ID:GHrama,项目名称:ameowsmeowl-2015,代码行数:27,代码来源:unzip_files.py


示例7: findBestPathFromWordToWord

    def findBestPathFromWordToWord( self, word, toWord ):
        """
        Do a breadth first search, which will find the shortest
        path between the nodes we are interested in
        This will only find a path if the words are
        linked by parent relationship
        you won't be able to find your cousins
        """
        queue = [word]
        previous = { word: word }
        while queue:
            node = queue.pop(0)
            if node == toWord: # If we've found our target word.
                # Work out how we got here.
                path = [node]
                while previous[node] != node:
                    node = previous[node]
                    path.append( node )
                return path

            # Continue on up the tree.
            for parent in self.getParentRelationships(node):
                # unless we've been to this parent before.
                if parent not in previous and parent not in queue:
                    previous[parent] = node
                    queue.append( parent )

        # We didn't find a path to our target word
        return None
开发者ID:xkjq,项目名称:WikidPad,代码行数:29,代码来源:WikiData.py


示例8: default_lib_path

def default_lib_path(data_dir: str, target: int, pyversion: int) -> List[str]:
    """Return default standard library search paths."""
    # IDEA: Make this more portable.
    path = List[str]()

    # Add MYPYPATH environment variable to library path, if defined.
    path_env = os.getenv('MYPYPATH')
    if path_env is not None:
        path[:0] = path_env.split(os.pathsep)

    if target in [ICODE, C]:
        # Add C back end library directory.
        path.append(os.path.join(data_dir, 'lib'))
    else:
        # Add library stubs directory. By convention, they are stored in the
        # stubs/x.y directory of the mypy installation.
        version_dir = '3.2'
        if pyversion < 3:
            version_dir = '2.7'
        path.append(os.path.join(data_dir, 'stubs', version_dir))
        path.append(os.path.join(data_dir, 'stubs-auto', version_dir))
        #Add py3.3 and 3.4 stubs
        if sys.version_info.major == 3:
            versions = ['3.' + str(x) for x in range(3, sys.version_info.minor + 1)]
            for v in versions:
                path.append(os.path.join(data_dir, 'stubs', v))

    # Add fallback path that can be used if we have a broken installation.
    if sys.platform != 'win32':
        path.append('/usr/local/lib/mypy')

    return path
开发者ID:mvcisback,项目名称:mypy,代码行数:32,代码来源:build.py


示例9: _find_path

    def _find_path(self, src, tgt):
        visited = set()
        to_visit = [src]
        came_from = {}
        while len(to_visit) > 0:
            elem = to_visit[0]
            del to_visit[0]

            if elem in visited:
                continue
            # if path found, redo path and return
            if elem is tgt and src in visited:  # elem in visited for the case where src = tgt
                path = []
                prev_elem = elem
                while prev_elem is not src:
                    path.append(prev_elem)
                    prev_elem = came_from[prev_elem]
                path.append(src)
                path.reverse()
                return path

            visited.add(elem)
            for outelem in elem.outset:
                came_from[outelem] = elem
                to_visit.append(outelem)
        return []  # if no path found, return an empty path
开发者ID:wx1988,项目名称:PMLAB,代码行数:26,代码来源:__simulate.py


示例10: default_lib_path

def default_lib_path(data_dir: str, pyversion: Tuple[int, int],
        python_path: bool) -> List[str]:
    """Return default standard library search paths."""
    # IDEA: Make this more portable.
    path = []  # type: List[str]

    auto = os.path.join(data_dir, 'stubs-auto')
    if os.path.isdir(auto):
        data_dir = auto

    # We allow a module for e.g. version 3.5 to be in 3.4/. The assumption
    # is that a module added with 3.4 will still be present in Python 3.5.
    versions = ["%d.%d" % (pyversion[0], minor)
                for minor in reversed(range(pyversion[1] + 1))]
    # E.g. for Python 3.5, try 2and3/, then 3/, then 3.5/, then 3.4/, 3.3/, ...
    for v in ['2and3', str(pyversion[0])] + versions:
        for lib_type in ['stdlib', 'builtins', 'third_party']:
            stubdir = os.path.join(data_dir, 'typeshed', lib_type, v)
            if os.path.isdir(stubdir):
                path.append(stubdir)

    # Add fallback path that can be used if we have a broken installation.
    if sys.platform != 'win32':
        path.append('/usr/local/lib/mypy')

    # Contents of Python's sys.path go last, to prefer the stubs
    # TODO: To more closely model what Python actually does, builtins should
    #       go first, then sys.path, then anything in stdlib and third_party.
    if python_path:
        path.extend(sys.path)

    return path
开发者ID:darjus,项目名称:mypy,代码行数:32,代码来源:build.py


示例11: extend_path

def extend_path(path, name):
    """Simpler version of the stdlib's :obj:`pkgutil.extend_path`.

    It does not support ".pkg" files, and it does not require an
    __init__.py (this is important: we want only one thing (pkgcore
    itself) to install the __init__.py to avoid name clashes).

    It also modifies the "path" list in place (and returns C{None})
    instead of copying it and returning the modified copy.
    """
    if not isinstance(path, list):
        # This could happen e.g. when this is called from inside a
        # frozen package.  Return the path unchanged in that case.
        return
    # Reconstitute as relative path.
    pname = os.path.join(*name.split('.'))

    for entry in sys.path:
        if not isinstance(entry, basestring) or not os.path.isdir(entry):
            continue
        subdir = os.path.join(entry, pname)
        # XXX This may still add duplicate entries to path on
        # case-insensitive filesystems
        if subdir not in path:
            path.append(subdir)
开发者ID:den4ix,项目名称:pkgcore,代码行数:25,代码来源:__init__.py


示例12: url_to_filename

  def url_to_filename(self, url):
    """ Map url to a unique file name/path. Register the directories in the path. """
    filename = re.sub(r'^https?://', '', url)
    filename = os.path.normpath(filename)
    
    path = []
    path_parts = filename.split("/")

    for idx, part in enumerate(path_parts):
      tries = 0
      unique_part = part
      new_path = "/".join(path + [part])

      while new_path in self.path_types and (self.path_types[new_path] == "file" or len(path_parts)-1 == idx):
        tries += 1
        unique_part = "%s.%d" % (part, tries)
        new_path = "/".join(path + [unique_part])

      if len(path_parts)-1 == idx:
        self.path_types[new_path] = "file"
      else:
        self.path_types[new_path] = "dir"

      path.append(unique_part)

    return "/".join(path)
开发者ID:alard,项目名称:warctozip-service,代码行数:26,代码来源:app.py


示例13: extend_path

def extend_path(path, name):
    if not isinstance(path, list):
        return path
    pname = os.path.join(*name.split('.'))
    sname = os.extsep.join(name.split('.'))
    sname_pkg = sname + os.extsep + 'pkg'
    init_py = '__init__' + os.extsep + 'py'
    path = path[:]
    for dir in sys.path:
        if not isinstance(dir, basestring) or not os.path.isdir(dir):
            continue
        subdir = os.path.join(dir, pname)
        initfile = os.path.join(subdir, init_py)
        if subdir not in path and os.path.isfile(initfile):
            path.append(subdir)
        pkgfile = os.path.join(dir, sname_pkg)
        if os.path.isfile(pkgfile):
            try:
                f = open(pkgfile)
            except IOError as msg:
                sys.stderr.write("Can't open %s: %s\n" % (pkgfile, msg))
            else:
                for line in f:
                    line = line.rstrip('\n')
                    if not line or line.startswith('#'):
                        continue
                    path.append(line)

                f.close()

    return path
开发者ID:bizonix,项目名称:DropBoxLibrarySRC,代码行数:31,代码来源:pkgutil.py


示例14: _read_xml

def _read_xml(stream):
    document = XmlNode()
    current_node = document
    path = []

    while not stream.atEnd():
        stream.readNext()

        if stream.isStartElement():
            node = XmlNode()
            attrs = stream.attributes()

            for i in xrange(attrs.count()):
                attr = attrs.at(i)
                node.attribs[_node_name(attr.name())] = unicode(attr.value())

            current_node.append_child(_node_name(stream.name()), node)
            path.append(current_node)
            current_node = node

        elif stream.isEndElement():
            current_node = path.pop()

        elif stream.isCharacters():
            current_node.text += unicode(stream.text())

    return document
开发者ID:Zialus,项目名称:picard,代码行数:27,代码来源:webservice.py


示例15: _read_structure_lazy

def _read_structure_lazy(infile=None, include_hosts=True):
    '''Determine and return the organizational structure from a given
    host file.
    '''

    path, hosts, structure = [], [], []

    lines = _read_lines_lazy(infile)
    for line in lines:
        if not _iscomment(line):
            if include_hosts:
                hosts.append(line)
            continue

        match = _match_open.search(line)
        if match:
            path.append(match.group(1))
            continue

        match = _match_close.search(line)
        if match:
            if include_hosts:
                yield (list(path), list(hosts))
                hosts = []
            else:
                yield list(path)

            path.pop()
    return
开发者ID:dhaffner,项目名称:hosts,代码行数:29,代码来源:hosts.py


示例16: chain_wires

def chain_wires(wires):
    assert wires.num_vertices > 0
    visited = np.zeros(wires.num_vertices, dtype=bool)
    path = [0]
    visited[0] = True
    while not np.all(visited):
        front = path[0]
        front_neighbors = wires.get_vertex_neighbors(int(front))
        for v in front_neighbors:
            if visited[v]:
                continue
            path.insert(0, v)
            visited[v] = True
            break
        end = path[-1]
        end_neighbors = wires.get_vertex_neighbors(int(end))
        for v in end_neighbors:
            if visited[v]:
                continue
            visited[v] = True
            path.append(v)
            break

    first_neighbors = wires.get_vertex_neighbors(int(path[0])).squeeze()
    if len(path) > 2 and path[-1] in first_neighbors:
        # Close the loop.
        path.append(path[0])

    path = wires.vertices[path]
    return path
开发者ID:mortezah,项目名称:PyMesh,代码行数:30,代码来源:minkowski_sum.py


示例17: mapping_to_alignment

def mapping_to_alignment(mapping, sam_file, region_fetcher):
    ''' Convert a mapping represented by a pysam.AlignedRead into an alignment. '''
    # The read indices in AlignedRead's aligned_pairs are relative to qstart.
    # Convert them to be absolute indices in seq.
    path = []
    mismatches = set()
    deletions = set()
    rname = sam_file.getrname(mapping.tid)
    for read_i, ref_i in mapping.aligned_pairs:
        if read_i != None:
            read_i = read_i + mapping.qstart
            if ref_i == None:
                ref_i = sw.GAP
            else:
                read_base = mapping.seq[read_i]
                ref_base = region_fetcher(rname, ref_i, ref_i + 1).upper()
                if read_base != ref_base:
                    mismatches.add((read_i, ref_i))

            path.append((read_i, ref_i))
        else:
            deletions.add(ref_i)

    alignment = {'path': path,
                 'XO': mapping.opt('XO'),
                 'XM': mapping.opt('XM'),
                 'is_reverse': mapping.is_reverse,
                 'mismatches': mismatches,
                 'deletions': deletions,
                 'rname': rname,
                 'query': mapping.seq,
                }
    return alignment
开发者ID:jeffhussmann,项目名称:sequencing,代码行数:33,代码来源:visualize_structure.py


示例18: GetCertificatePath

    def GetCertificatePath(self, cert):
        """
        Return the certification path for cert.
        """

        path = []
        repo = self.GetCertificateRepository()
        c = cert
        checked = {}
        while 1:
            subj = str(c.GetSubject())
            path.append(c)
            if c.GetSubject().as_der() == c.GetIssuer().as_der():
                break

            # If we come back to a place we've been before, we're in a cycle
            # and won't get anywhere. Bail.

            if subj in checked:
                return ""
            checked[subj] = 1
            
            issuers = repo.FindCertificatesWithSubject(str(c.GetIssuer()))

            validIssuers = filter(lambda x: not x.IsExpired(), issuers)

            # Find an issuer to return. If none is valid, pick one to return.
            if len(validIssuers) == 0:
                if len(issuers) > 0:
                    path.append(issuers[0])
                break
            
            c = issuers[0]

        return path
开发者ID:aabhasgarg,项目名称:accessgrid,代码行数:35,代码来源:CertificateManager.py


示例19: read_mda

 def read_mda(self, attribute):
     lines = attribute.split('\n')
     mda = {}
     current_dict = mda
     path = []
     for line in lines:
         if not line:
             continue
         if line == 'END':
             break
         key, val = line.split('=')
         key = key.strip()
         val = val.strip()
         try:
             val = eval(val)
         except NameError:
             pass
         if key in ['GROUP', 'OBJECT']:
             new_dict = {}
             path.append(val)
             current_dict[val] = new_dict
             current_dict = new_dict
         elif key in ['END_GROUP', 'END_OBJECT']:
             if val != path[-1]:
                 raise SyntaxError
             path = path[:-1]
             current_dict = mda
             for item in path:
                 current_dict = current_dict[item]
         elif key in ['CLASS', 'NUM_VAL']:
             pass
         else:
             current_dict[key] = val
     return mda
开发者ID:pytroll,项目名称:satpy,代码行数:34,代码来源:hdfeos_l1b.py


示例20: test_func_dir

def test_func_dir():
    # Test the creation of the memory cache directory for the function.
    memory = Memory(cachedir=env["dir"], verbose=0)
    memory.clear()
    path = __name__.split(".")
    path.append("f")
    path = os.path.join(env["dir"], "joblib", *path)

    g = memory.cache(f)
    # Test that the function directory is created on demand
    yield nose.tools.assert_equal, g._get_func_dir(), path
    yield nose.tools.assert_true, os.path.exists(path)

    # Test that the code is stored.
    # For the following test to be robust to previous execution, we clear
    # the in-memory store
    _FUNCTION_HASHES.clear()
    yield nose.tools.assert_false, g._check_previous_func_code()
    yield nose.tools.assert_true, os.path.exists(os.path.join(path, "func_code.py"))
    yield nose.tools.assert_true, g._check_previous_func_code()

    # Test the robustness to failure of loading previous results.
    dir, _ = g.get_output_dir(1)
    a = g(1)
    yield nose.tools.assert_true, os.path.exists(dir)
    os.remove(os.path.join(dir, "output.pkl"))
    yield nose.tools.assert_equal, a, g(1)
开发者ID:apetcho,项目名称:joblib,代码行数:27,代码来源:test_memory.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python path.basename函数代码示例发布时间:2022-05-25
下一篇:
Python path.abspath函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap