pathlib(pathlib2对于 Python 版本 < 3.4)主要由四个与路径 、和Path( PosixPathin )直接相关的类组成。如果您将其中的每一个子类化并以下列方式复制和调整代码:WindowsPathPurePathBasePathpathlib2Path.__new__()PurePath._parse_args()
import os
import sys
if sys.version_info < (3, 4):
import pathlib2 as pathlib
else:
import pathlib
class PurePath(pathlib.Path):
__slots__ = ()
types_to_stringify = [int]
@classmethod
def _parse_args(cls, args):
# This is useful when you don't want to create an instance, just
# canonicalize some constructor arguments.
parts = []
for a in args:
if isinstance(a, pathlib.PurePath):
parts += a._parts
elif sys.version_info < (3,) and isinstance(a, basestring):
# Force-cast str subclasses to str (issue #21127)
parts.append(str(a))
elif sys.version_info >= (3, 4) and isinstance(a, str):
# Force-cast str subclasses to str (issue #21127)
parts.append(str(a))
elif isinstance(a, tuple(PurePath.types_to_stringify)):
parts.append(str(a))
else:
try:
parts.append(a)
except:
raise TypeError(
"argument should be a path or str object, not %r"
% type(a))
return cls._flavour.parse_parts(parts)
class WindowsPath(PurePath, pathlib.PureWindowsPath):
__slots__ = ()
class PosixPath(PurePath, pathlib.PurePosixPath):
__slots__ = ()
class Path(pathlib.Path):
__slots__ = ()
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
您将拥有一个Path已经理解int并且可以用来做的事情:
from py._path.local import LocalPath
# extend the types to be converted to string on the fly
PurePath.types_to_stringify.extend([LocalPath, bool])
tmpdir = LocalPath('/var/tmp/abc')
p = Path(tmpdir) / 14 / False / 'testfile.yaml'
print(p)
要得到:
/var/tmp/abc/14/False/testfile.yaml
(您需要安装pathlib2版本 < 3.4 的软件包才能使用这些软件包)。
以上Path可以open(p)在 Python 3.6 中使用。
Adapting为您提供对( ) 以及诸如 等方法的_parse_args自动支持。/__truediv__joinpath()relative_to()