Advertisement
treyhunner

Extending pathlib.Path

Apr 11th, 2019
821
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.03 KB | None | 0 0
  1. import pathlib
  2. import os
  3. from os.path import commonprefix, relpath
  4. import shutil
  5.  
  6.  
  7. class Path(pathlib.Path):
  8.  
  9.     def __new__(cls, *args, **kwargs):
  10.         if cls is Path:
  11.             cls = WindowsPath if os.name == 'nt' else PosixPath
  12.         self = cls._from_parts(args, init=False)
  13.         if not self._flavour.is_supported:
  14.             raise NotImplementedError("cannot instantiate %r on your system"
  15.                                       % (cls.__name__,))
  16.         self._init()
  17.         return self
  18.  
  19.     def walk(self):
  20.         for path in self.iterdir():
  21.             if path.is_dir():
  22.                 yield from path.walk()
  23.             else:
  24.                 yield path
  25.  
  26.     def absolute(self):
  27.         raise AttributeError("Use resolve, not absolute")
  28.  
  29.     def chdir(self):
  30.         os.chdir(self)
  31.         return Path.cwd()
  32.  
  33.     def relative_to(self, other):
  34.         return Path(relpath(self, other))
  35.  
  36.     def common_prefix(self, other):
  37.         return Path(commonprefix((self, other)))
  38.  
  39.     def copy(self, destination, *,
  40.              follow_symlinks=True, preserve_metadata=True):
  41.         copy = shutil.copy2 if preserve_metadata else shutil.copy
  42.         if self.is_dir():
  43.             shutil.copytree(self, destination, copy_function=copy,
  44.                             symlinks=not follow_symlinks)
  45.         else:
  46.             copy(self, destination, follow_symlinks=follow_symlinks)
  47.  
  48.     def move(self, destination, *, preserve_metadata=True):
  49.         copy = shutil.copy2 if preserve_metadata else shutil.copy
  50.         shutil.move(self, destination, copy_function=copy)
  51.  
  52.     def rmdir(self, recursive=False, ignore_errors=False):
  53.         if recursive:
  54.             shutil.rmtree(self, ignore_errors=ignore_errors)
  55.         else:
  56.             try:
  57.                 super().rmdir()
  58.             except Exception:
  59.                 if not ignore_errors:
  60.                     raise
  61.  
  62.  
  63. class PosixPath(Path, pathlib.PurePosixPath):
  64.     __slots__ = ()
  65.  
  66.  
  67. class WindowsPath(Path, pathlib.PureWindowsPath):
  68.     __slots__ = ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement