The following code is what I tried first, but some_path.with_suffix('.jpg')
obviously returns a pathlib.PosixPath
object (I'm on Linux) instead of my version of PosixPath
, because I didn't redefine with_suffix
. Do I have to copy everything from pathlib
or is there a better way?
import os
import pathlib
from shutil import rmtree
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 with_stem(self, stem):
"""
Return a new path with the stem changed.
The stem is the final path component, minus its last suffix.
"""
if not self.name:
raise ValueError("%r has an empty name" % (self,))
return self._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [stem + self.suffix])
def rmtree(self, ignore_errors=False, onerror=None):
"""
Delete the entire directory even if it contains directories / files.
"""
rmtree(str(self), ignore_errors, onerror)
class PosixPath(Path, pathlib.PurePosixPath):
__slots__ = ()
class WindowsPath(Path, pathlib.PureWindowsPath):
__slots__ = ()
With Pathlib, you can do all the basic file handling tasks that you did before, and there are some other features that don't exist in the OS module. The key difference is that Pathlib is more intuitive and easy to use. All the useful file handling methods belong to the Path objects.
Since Python 3.4, pathlib has been available in the standard library. With pathlib , file paths can be represented by proper Path objects instead of plain strings as before. These objects make code dealing with file paths: Easier to read, especially because / is used to join paths together.
Pathlib module in Python provides various classes representing file system paths with semantics appropriate for different operating systems. This module comes under Python's standard utility modules.
The Pathlib module can deal with absolute as well as relative paths. An absolute path begins from the root directory and specifies the complete directory tree, whereas a relative path, as the name suggests, is the path of a file relative to another file or directory (usually the current directory).
Is some_path
an instance of your version of Path
?
I tested with the following 2 lines appended to your codes:
p = Path('test.foo')
print(type(p.with_suffix('.bar')))
Result is correct: <class '__main__.PosixPath'>
Only when using p = pathlib.Path('test.foo')
, result is <class 'pathlib.PosixPath'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With