我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用posixpath.sep()。
def relto(self, relpath): """ return a string which is the relative part of the path to the given 'relpath'. """ if not isinstance(relpath, (str, PathBase)): raise TypeError("%r: not a string or path object" %(relpath,)) strrelpath = str(relpath) if strrelpath and strrelpath[-1] != self.sep: strrelpath += self.sep #assert strrelpath[-1] == self.sep #assert strrelpath[-2] != self.sep strself = self.strpath if sys.platform == "win32" or getattr(os, '_name', None) == 'nt': if os.path.normcase(strself).startswith( os.path.normcase(strrelpath)): return strself[len(strrelpath):] elif strself.startswith(strrelpath): return strself[len(strrelpath):] return ""
def bestrelpath(self, dest): """ return a string which is a relative path from self (assumed to be a directory) to dest such that self.join(bestrelpath) == dest and if not such path can be determined return dest. """ try: if self == dest: return os.curdir base = self.common(dest) if not base: # can be the case on windows return str(dest) self2base = self.relto(base) reldest = dest.relto(base) if self2base: n = self2base.count(self.sep) + 1 else: n = 0 l = [os.pardir] * n if reldest: l.append(reldest) target = dest.sep.join(l) return target except AttributeError: return str(dest)
def __call__(self, path): pattern = self.pattern if (pattern.find(path.sep) == -1 and iswin32 and pattern.find(posixpath.sep) != -1): # Running on Windows, the pattern has no Windows path separators, # and the pattern has one or more Posix path separators. Replace # the Posix path separators with the Windows path separator. pattern = pattern.replace(posixpath.sep, path.sep) if pattern.find(path.sep) == -1: name = path.basename else: name = str(path) # path.strpath # XXX svn? if not os.path.isabs(pattern): pattern = '*' + path.sep + pattern return py.std.fnmatch.fnmatch(name, pattern)
def relpath(path, start=curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") if type(start) is unicode: start_list = unicode_abspath(start).split(sep) else: start_list = abspath(start).split(sep) if type(path) is unicode: path_list = unicode_abspath(path).split(sep) else: path_list = abspath(path).split(sep) # Work out how much of the filepath is shared by start and path. i = len(commonprefix([start_list, path_list])) rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list) # End Futures
def test_all_table_entries(harness, files, request_uri, expected): # set up the specified files realfiles = tuple([ f if f.endswith('/') else (f, GENERIC_SPT) for f in files ]) harness.fs.www.mk(*realfiles) try: state = harness._hit('GET', request_uri, want='state', return_after='dispatch_path_to_filesystem') except exceptions.NotFound: result = '404' except exceptions.Redirect as err: result = '302 ' + err.message else: result = '200' path = format_result(**state) if os.sep != posixpath.sep: path = path.replace(os.sep, posixpath.sep) path = path[len(harness.fs.www.root)+1:] if path: result += " " + path if expected.endswith("*"): expected = expected[:-1] assert result == expected, "Requesting %r, got %r instead of %r" % (request_uri, result, expected)
def path_advance(thepath, sep=os.sep): '''generator to iterate over a file path forwards :param str thepath: the path to navigate forwards :param str sep: *Default: os.sep* - the path separator to use :returns: (iter)able of strings ''' # handle a direct path pre = '' if thepath[0] == sep: pre = sep curpath = '' parts = thepath.split(sep) if pre: if parts[0]: parts[0] = pre + parts[0] else: parts[1] = pre + parts[1] for part in parts: curpath = os.path.join(curpath, part) if curpath: yield curpath
def path_retreat(thepath, sep=os.sep): '''generator to iterate over a file path in reverse :param str thepath: the path to retreat over :param str sep: *Default: os.sep* - the path separator to use :returns: (iter)able of strings ''' pre = '' if thepath[0] == sep: pre = sep parts = thepath.split(sep) while parts: if os.path.join(*parts): yield '%s%s' % (pre, os.path.join(*parts)) parts = parts[:-1]
def reparent(newparent, oldpath): '''when copying or moving a directory structure, you need to re-parent the oldpath. When using os.path.join to calculate this new path, the appearance of a / root path at the beginning of oldpath, supplants the newparent and we don't want this to happen, so we need to make the oldpath root appear as a child of the newparent. :param: str newparent: the new parent location for oldpath (target) :param str oldpath: the path being adopted by newparent (source) :returns: (str) resulting adoptive path ''' if oldpath[0] in (posixpath.sep, ntpath.sep): oldpath = '.' + oldpath return os.path.join(newparent, oldpath)
def relto(self, relpath): """ return a string which is the relative part of the path to the given 'relpath'. """ if not isinstance(relpath, (str, PathBase)): raise TypeError("%r: not a string or path object" %(relpath,)) strrelpath = str(relpath) if strrelpath and strrelpath[-1] != self.sep: strrelpath += self.sep #assert strrelpath[-1] == self.sep #assert strrelpath[-2] != self.sep strself = str(self) if sys.platform == "win32" or getattr(os, '_name', None) == 'nt': if os.path.normcase(strself).startswith( os.path.normcase(strrelpath)): return strself[len(strrelpath):] elif strself.startswith(strrelpath): return strself[len(strrelpath):] return ""
def __call__(self, path): pattern = self.pattern if (pattern.find(path.sep) == -1 and iswin32 and pattern.find(posixpath.sep) != -1): # Running on Windows, the pattern has no Windows path separators, # and the pattern has one or more Posix path separators. Replace # the Posix path separators with the Windows path separator. pattern = pattern.replace(posixpath.sep, path.sep) if pattern.find(path.sep) == -1: name = path.basename else: name = str(path) # path.strpath # XXX svn? if not os.path.isabs(pattern): pattern = '*' + path.sep + pattern return fnmatch.fnmatch(name, pattern)
def get_template(self, uri): """Return a :class:`.Template` object corresponding to the given ``uri``. .. note:: The ``relativeto`` argument is not supported here at the moment. """ try: if self.filesystem_checks: return self._check(uri, self._collection[uri]) else: return self._collection[uri] except KeyError: u = re.sub(r'^\/+', '', uri) for dir in self.directories: # make sure the path seperators are posix - os.altsep is empty # on POSIX and cannot be used. dir = dir.replace(os.path.sep, posixpath.sep) srcfile = posixpath.normpath(posixpath.join(dir, u)) if os.path.isfile(srcfile): return self._load(srcfile, uri) else: raise exceptions.TopLevelLookupException( "Cant locate template for uri %r" % uri)
def PullAppFilesImpl(device, package, files, directory): device_dir = device.GetApplicationDataDirectory(package) host_dir = os.path.join(directory, str(device)) for f in files: device_file = posixpath.join(device_dir, f) host_file = os.path.join(host_dir, *f.split(posixpath.sep)) host_file_base, ext = os.path.splitext(host_file) for i in itertools.count(): host_file = '%s_%d%s' % (host_file_base, i, ext) if not os.path.exists(host_file): break device.PullFile(device_file, host_file)
def _extract_local_archive(working_dir, cleanup_functions, env_name, local_archive): """Helper internal function for extracting a zipfile and ensure that a cleanup is queued. Parameters ---------- working_dir : str cleanup_functions : List[() -> NoneType] env_name : str local_archive : str """ with zipfile.ZipFile(local_archive) as z: z.extractall(working_dir) archive_filenames = z.namelist() root_elements = {m.split(posixpath.sep, 1)[0] for m in archive_filenames} abs_archive_filenames = [os.path.abspath(os.path.join(working_dir, f)) for f in root_elements] def cleanup(): for fn in abs_archive_filenames: if os.path.isdir(fn): shutil.rmtree(fn) else: os.unlink(fn) cleanup_functions.append(cleanup) env_dir = os.path.join(working_dir, env_name) # Because of a python deficiency (Issue15795), the execute bits aren't # preserved when the zip file is unzipped. Need to add them back here. _fix_permissions(env_dir) return env_dir
def Print(self, file=sys.stdout): """Prints a reprentation of this object to file, adhering to Xcode output formatting. """ self.VerifyHasRequiredProperties() if self._should_print_single_line: # When printing an object in a single line, Xcode doesn't put any space # between the beginning of a dictionary (or presumably a list) and the # first contained item, so you wind up with snippets like # ...CDEF = {isa = PBXFileReference; fileRef = 0123... # If it were me, I would have put a space in there after the opening # curly, but I guess this is just another one of those inconsistencies # between how Xcode prints PBXFileReference and PBXBuildFile objects as # compared to other objects. Mimic Xcode's behavior here by using an # empty string for sep. sep = '' end_tabs = 0 else: sep = '\n' end_tabs = 2 # Start the object. For example, '\t\tPBXProject = {\n'. self._XCPrint(file, 2, self._XCPrintableValue(2, self) + ' = {' + sep) # "isa" isn't in the _properties dictionary, it's an intrinsic property # of the class which the object belongs to. Xcode always outputs "isa" # as the first element of an object dictionary. self._XCKVPrint(file, 3, 'isa', self.__class__.__name__) # The remaining elements of an object dictionary are sorted alphabetically. for property, value in sorted(self._properties.iteritems()): self._XCKVPrint(file, 3, property, value) # End the object. self._XCPrint(file, end_tabs, '};\n')
def relpath(path, start=curdir): """Return a relative version of a path""" if not path: raise ValueError("no path specified") start_list = abspath(start).split(sep) path_list = abspath(path).split(sep) # Work out how much of the filepath is shared by start and path. i = len(commonprefix([start_list, path_list])) rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list)
def path_make_absolute(path): p = os.path.abspath(path) if p[-1] == os.path.sep: return p else: return p + os.path.sep
def path_make_relative(path): p = relpath(path) if p[-1] == os.path.sep: return p else: return p + os.path.sep
def _relpath(self, path, start): """An alternative to os.path.relpath()""" if not path: raise ValueError("no path specified") start_list = posixpath.abspath(start).split(posixpath.sep) path_list = posixpath.abspath(path).split(posixpath.sep) # Work out how much of the filepath is shared by start and path. i = len(posixpath.commonprefix([start_list, path_list])) rel_list = [posixpath.pardir] * (len(start_list) - i) + path_list[i:] if not rel_list: return posixpath.curdir return posixpath.join(*rel_list)
def mkdir_p(path): dirs = path.split(os.sep) parent='' for d in dirs: path = parent+d if os.path.exists(path): if not os.path.isdir(path): raise BaseException("Path component '"+parent+d+"' is a file") else: os.mkdir(path) parent = parent + d + posixpath.sep