Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pathlib
- import os
- from os.path import commonprefix, relpath
- import shutil
- class Path(pathlib.Path):
- def __new__(cls, *args, **kwargs):
- if cls is Path:
- cls = WindowsPath if os.name == 'nt' else PosixPath
- self = cls._from_parts(args, init=False)
- if not self._flavour.is_supported:
- raise NotImplementedError("cannot instantiate %r on your system"
- % (cls.__name__,))
- self._init()
- return self
- def walk(self):
- for path in self.iterdir():
- if path.is_dir():
- yield from path.walk()
- else:
- yield path
- def absolute(self):
- raise AttributeError("Use resolve, not absolute")
- def chdir(self):
- os.chdir(self)
- return Path.cwd()
- def relative_to(self, other):
- return Path(relpath(self, other))
- def common_prefix(self, other):
- return Path(commonprefix((self, other)))
- def copy(self, destination, *,
- follow_symlinks=True, preserve_metadata=True):
- copy = shutil.copy2 if preserve_metadata else shutil.copy
- if self.is_dir():
- shutil.copytree(self, destination, copy_function=copy,
- symlinks=not follow_symlinks)
- else:
- copy(self, destination, follow_symlinks=follow_symlinks)
- def move(self, destination, *, preserve_metadata=True):
- copy = shutil.copy2 if preserve_metadata else shutil.copy
- shutil.move(self, destination, copy_function=copy)
- def rmdir(self, recursive=False, ignore_errors=False):
- if recursive:
- shutil.rmtree(self, ignore_errors=ignore_errors)
- else:
- try:
- super().rmdir()
- except Exception:
- if not ignore_errors:
- raise
- class PosixPath(Path, pathlib.PurePosixPath):
- __slots__ = ()
- class WindowsPath(Path, pathlib.PureWindowsPath):
- __slots__ = ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement