How to use the pathlib2.PurePath function in pathlib2

To help you get started, we’ve selected a few pathlib2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mcmtroffaes / pathlib2 / tests / test_pathlib2.py View on Github external
self.assertIs(True, P('NUL').is_reserved())
        self.assertIs(True, P('NUL.txt').is_reserved())
        self.assertIs(True, P('com1').is_reserved())
        self.assertIs(True, P('com9.bar').is_reserved())
        self.assertIs(False, P('bar.com9').is_reserved())
        self.assertIs(True, P('lpt1').is_reserved())
        self.assertIs(True, P('lpt9.bar').is_reserved())
        self.assertIs(False, P('bar.lpt9').is_reserved())
        # Only the last component matters
        self.assertIs(False, P('c:/NUL/con/baz').is_reserved())
        # UNC paths are never reserved
        self.assertIs(False, P('//my/share/nul/con/aux').is_reserved())


class PurePathTest(_BasePurePathTest, unittest.TestCase):
    cls = pathlib.PurePath

    def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(
            type(p),
            pathlib.PureWindowsPath
            if os.name == 'nt' else pathlib.PurePosixPath)

    def test_different_flavours_unequal(self):
        p = pathlib.PurePosixPath('a')
        q = pathlib.PureWindowsPath('a')
        self.assertNotEqual(p, q)

    @unittest.skipIf(sys.version_info < (3, 0),
                     'Most types are orderable in Python 2')
    def test_different_flavours_unordered(self):
github lrq3000 / pyFileFixity / pyFileFixity / lib / aux_funcs.py View on Github external
def path2unix(path, nojoin=False, fromwinpath=False):
    '''From a path given in any format, converts to posix path format
    fromwinpath=True forces the input path to be recognized as a Windows path (useful on Unix machines to unit test Windows paths)'''
    if fromwinpath:
        pathparts = list(PureWindowsPath(path).parts)
    else:
        pathparts = list(PurePath(path).parts)
    if nojoin:
        return pathparts
    else:
        return posixpath.join(*pathparts)
github floydhub / floyd-cli / floyd / client / files.py View on Github external
def matches_glob_list(path, glob_list):
    """
    Given a list of glob patterns, returns a boolean
    indicating if a path matches any glob in the list
    """
    for glob in glob_list:
        try:
            if PurePath(path).match(glob):
                return True
        except TypeError:
            pass
    return False
github airbnb / streamalert / rules / helpers / base.py View on Github external
NOTE: Intended for filepaths with wildcards where fnmatch is too greedy.
    Especially useful in cases where a username in a filepath may need to be wildcarded.

    For example;
    path_matches_any('/Users/foobar/path/to/file', {'/Users/*/path/*/file'}) == True

    Args:
        text (str): Text to examine
        patterns (iterable): Collection of string patterns, compatible with fnmatch (* wildcards)

    Returns:
        bool: True if the text matches at least one of the patterns, False otherwise.
    """
    if not isinstance(text, basestring):
        return False
    return any(pathlib2.PurePath(text).match(pattern) for pattern in patterns)
github tkf / JuliaManager.jl / jlm / src / jlm / utils.py View on Github external
from typing import List, Tuple, Union

Cmd = List[str]

_Pathish = Union[str, pathlib.PurePath]

try:
    Pathish = (str, os.PathLike)  # type: Tuple
except AttributeError:
    Pathish = (str, pathlib.PurePath)
    try:
        import pathlib2  # type: ignore
    except ImportError:
        pass
    else:
        Pathish += (pathlib2.PurePath,)

iswindows = os.name == "nt"  # type: bool
isapple = sys.platform == "darwin"  # type: bool

# See: Libdl.jl
if isapple:
    dlext = "dylib"
elif iswindows:
    dlext = "dll"
else:
    dlext = "so"


def pathstr(path: _Pathish) -> str:
    if not isinstance(path, Pathish):
        raise ValueError("Not a path or a string:\n{!r}".format(path))
github nodepy / nodepy / src / nodepy / utils / path / urlpath.py View on Github external
sep = '/'
  altsep = ''
  has_drv = False
  pathmod = posixpath
  is_supported = True

  def splitroot(self, part, sep=sep):
    res = urlparse(part)
    return (
      res.scheme + '://' if res.scheme else '',
      res.netloc + '/' if res.netloc else '',
      urlunparse(('', '', res.path, res.params, res.query, res.fragment))
    )


class PureUrlPath(pathlib.PurePath):
  _flavour = _UrlFlavour()
  __slots__ = ()

  def absolute(self):
    return self

  def is_absolute(self):
    return True


class UrlPath(pathlib.Path, PureUrlPath):
  __slots__ = ()

  # Wrapper for the socket._fileobject returned from #urlopen().
  # Necessary in Python 2 because socket._fileobject does not support
  # readable(), writable() and seekable(), and without this protocol it
github ipfs / py-ipfs-http-client / ipfshttpclient / utils.py View on Github external
if hasattr(os, "PathLike"):  #PY36+
	path_obj_types += (os.PathLike,)

	def convert_path(path):
		# Not needed since all system APIs also accept an `os.PathLike`
		return path
else:  #PY35
	try:  #PY2: doesn't have `pathlib`
		import pathlib
		path_obj_types += (pathlib.PurePath,)
	except ImportError:
		pass
	# Independently maintained forward-port of `pathlib` for Py27 and others
	try:
		import pathlib2
		path_obj_types += (pathlib2.PurePath,)
	except ImportError:
		pass
	
	def convert_path(path):
		# `pathlib`'s PathLike objects need to be treated specially and
		# converted to strings when interacting with system APIs
		return str(path) if isinstance(path, path_obj_types) else path
path_types = path_str_types + path_obj_types


def guess_mimetype(filename):
	"""Guesses the mimetype of a file based on the given ``filename``.

	.. code-block:: python

		>>> guess_mimetype('example.txt')