pathlib
(和pathlib2
爲Python版本< 3.4)主要由直接相關的路徑Path
,PosixPath
,(在pathlib2
BasePath
)WindowsPath
和PurePath
四類。如果你繼承每一種複製並適應以下列方式爲Path.__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
可以在Python 3.6中用作open(p)
。
適應_parse_args
給你喜歡的joinpath()
/
(__truediv__
)自動支持以及方法,relative_to()
等
雖然它看起來比我的解決方案更簡單,但它不會抱怨任何可以表示爲字符串的**類型。如果你想使用'joinpath()','realtive_to()'等,你還必須引入每一個定義。 – Anthon