Python 3.4+:扩展pathlib.Path

时间:2014-11-15 18:19:35

标签: python python-3.x path pathlib

以下代码是我首先尝试的,但是some_path.with_suffix('.jpg')显然会返回pathlib.PosixPath对象(我在Linux上)而不是我的PosixPath版本,因为我没有& #39;重新定义with_suffix。我是否必须复制pathlib中的所有内容,或者有更好的方法吗?

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__ = ()

1 个答案:

答案 0 :(得分:1)

some_path是您的Path版本的实例吗?

我测试了你的代码附加了以下2行:

p = Path('test.foo')
print(type(p.with_suffix('.bar')))

结果是正确的:<class '__main__.PosixPath'>

仅在使用p = pathlib.Path('test.foo')时,结果为<class 'pathlib.PosixPath'>