7

以下代码是我首先尝试的,但some_path.with_suffix('.jpg')显然返回一个pathlib.PosixPath对象(我在 Linux 上)而不是我的版本PosixPath,因为我没有重新定义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__ = ()
4

1 回答 1

1

some_path您的版本的实例Path吗?

我测试了以下两行附加到您的代码:

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

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

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

于 2014-12-23T06:53:59.387 回答